package com.info.zhiduoduo.admin.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Condition;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.info.zhiduoduo.admin.model.formbean.account.MakerLabelFormBean;
import com.info.zhiduoduo.admin.model.formbean.maker.*;
import com.info.zhiduoduo.admin.model.formbean.taxer.OpenTaxerFormBean;
import com.info.zhiduoduo.common.baidusdk.BankcardService;
import com.info.zhiduoduo.common.baidusdk.domain.BankcardResponse;
import com.info.zhiduoduo.common.configs.CommonConfig;
import com.info.zhiduoduo.common.configs.UploadPathConfig;
import com.info.zhiduoduo.common.configs.WhetherTestConfig;
import com.info.zhiduoduo.common.configs.YunKongConfig;
import com.info.zhiduoduo.common.configs.ZddUrlConfig;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.maker.MakerEntrustTaxVideoState;
import com.info.zhiduoduo.common.constants.maker.MakerType;
import com.info.zhiduoduo.common.constants.maker.StudioState;
import com.info.zhiduoduo.common.constants.project.CalcAmountType;
import com.info.zhiduoduo.common.constants.system.UserType;
import com.info.zhiduoduo.common.exception.Asserts;
import com.info.zhiduoduo.common.exception.SmartException;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.*;
import com.info.zhiduoduo.core.service.*;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.core.service.impl.BankCardElementCertificationService;
import com.info.zhiduoduo.core.service.impl.CeoNoticeService;
import com.info.zhiduoduo.core.service.wxmessage.WxTaxerWxMessageServiceImpl;
import com.info.zhiduoduo.repository.dto.maker.*;
import com.info.zhiduoduo.repository.entity.company.Company;
import com.info.zhiduoduo.repository.entity.company.CompanyAccount;
import com.info.zhiduoduo.repository.entity.company.CompanyParty;
import com.info.zhiduoduo.repository.entity.company.CompanyProject;
import com.info.zhiduoduo.repository.entity.crowdsource.CrowdsourceAccount;
import com.info.zhiduoduo.repository.entity.maker.*;
import com.info.zhiduoduo.repository.entity.partner.Partner;
import com.info.zhiduoduo.repository.entity.system.SystemManager;
import com.info.zhiduoduo.repository.entity.taxer.TaxerInviteCode;
import com.info.zhiduoduo.repository.mapper.company.CompanyAccountMapper;
import com.info.zhiduoduo.repository.mapper.company.CompanyProjectMapper;
import com.info.zhiduoduo.repository.mapper.crm.CrmSystemManagerMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceInvoiceMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceTradeRecordMapper;
import com.info.zhiduoduo.repository.mapper.entrustmentproject.EntrustmentProjectItemMapper;
import com.info.zhiduoduo.repository.mapper.invoice.InvoiceMapper;
import com.info.zhiduoduo.repository.mapper.maker.*;
import com.info.zhiduoduo.repository.mapper.system.ManagerMapper;
import com.info.zhiduoduo.repository.mapper.taxer.TaxerInviteCodeMapper;
import com.info.zhiduoduo.repository.mapper.taxer.TaxerInvoiceMapper;
import com.info.zhiduoduo.wxsdk.utils.LogUtil;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class MakerService extends BaseService {

	@Autowired
	SystemService systemService;
	@Autowired
	CommonService commonService;
	@Autowired
	WxMessageService wxMessageService;
	@Autowired
	WxTaxerWxMessageServiceImpl wxTaxerMessageService;
	@Autowired
	WxCrowdsourceMessageService wxCrowdsourceMessageService;
	@Autowired
	CeoNoticeService ceoNoticeService;
	@Autowired
	InvoiceInventoryService invoiceInventoryService;
	@Autowired
	CrowdsourceService crowdsourceService;
	@Autowired
	BankcardService bankcardService;
	@Autowired
	CoreProjectService coreProjectService;

	@Resource
	MakerMapper makerMapper;
	@Resource
	MakerStudioMapper makerStudioMapper;
	@Resource
	MakerAccountMapper makerAccountMapper;
	@Resource
	CoreCompanyService coreCompanyService;
	@Resource
	MakerBankcardMapper makerBankcardMapper;
	@Resource
	MakerWithdrawMapper makerWithdrawMapper;
	@Resource
	MakerFinishTaxMapper makerFinishTaxMapper;
	@Resource
	TaxerInviteCodeMapper taxerInviteCodeMapper;
	@Resource
	MakerTagMapper makerTagMapper;
	@Resource
	MakerRescissionApplyMapper makerRescissionApplyMapper;
	@Resource
	InvoiceMapper invoiceMapper;
	@Resource
	CompanyProjectMapper companyProjectMapper;
	@Resource
	TaxerInvoiceMapper taxerInvoiceMapper;
	@Resource
	CrowdsourceProjectMapper crowdsourceProjectMapper;
	@Resource
	CrowdsourceInvoiceMapper crowdsourceInvoiceMapper;
	@Resource
	CrowdsourceTradeRecordMapper crowdsourceTradeRecordMapper;
	@Resource
	ManagerMapper managerMapper;
	@Resource
	CustodianModificationRecordMapper custodianModificationRecordMapper;
	@Resource
	private CompanyAccountMapper companyAccountMapper;
	@Resource
	private CrmSystemManagerMapper crmSystemManagerMapper;
	@Resource
	private EntrustmentProjectItemMapper entrustmentProjectItemMapper;

	@Resource
	WhetherTestConfig whetherTestConfig;
	@Autowired
	CommonConfig commonConfig;
	@Resource
	ZddUrlConfig zddUrlConfig;
	@Resource
	YunKongConfig yunKongConfig;
	@Autowired
	UploadPathConfig uploadPathConfig;

	@Autowired
	BankCardElementCertificationService bankCardElementCertificationService;

	public SmartResult getUserInfo(BaseSimpleFormBean<Integer> formBean) {

		Integer userid = formBean.getReqdata();
		if (userid == null || userid <= 0) return errorParamSmartResult();

		MakerDetailDto userInfo = getUserInfo(userid);

		if (null == userInfo) return smartResult(StatusMsg.StatusMsg_201);

		return smartResult(userInfo);
	}

	public MakerDetailDto getUserInfo(int userid) {
		MakerDetailDto user = makerMapper.getUserDetail(userid);
		if (user == null) {
			return null;
		}
		if (user.getMakerType() == MakerType.TAXER && StringUtil.isNotEmpty(user.getTaxerInviteCode())) {
			TaxerInviteCode taxerInviteCode = taxerInviteCodeMapper.selectByCode(user.getTaxerInviteCode());
			if (taxerInviteCode != null) {
				user.setTaxerInviteName(taxerInviteCode.getInviteName())
						.setTaxerInviteAmount(taxerInviteCode.getAmount())
						.setTaxerInviteRemark(taxerInviteCode.getRemark());
			}
		}
		user.setTagList(makerTagMapper.getUserTagList(userid));
		return user;
	}

	/**
	 * 获取未审核,审核中的用户列表
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult<VerifyingMakerDto> getVerifyingList(BaseSimpleFormBean<MakerListFormBean> formBean) {
		MakerListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		Integer makerType = reqdata.getMakerType();
		if (makerType == null || makerType == 0) makerType = MakerType.INTELL;

		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		String name = reqdata.getName();
		int state = reqdata.getState();
		String inviter = reqdata.getInviter();
		String bindcompname = reqdata.getBindcompname();
		String phone = reqdata.getPhone();
		Integer temporaryLogin = reqdata.getTemporaryLogin();

		Integer openingLocation = reqdata.getOpeningLocation();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<VerifyingMakerDto> list = makerAccountMapper.getVerifyList(makerType, name, inviter, state, startDate, endDate, bindcompname,
				phone, openingLocation, "", temporaryLogin);
		return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
	}

	/**
	 * 获取审核详情
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult<VerifyingMakerDto> getVerifyingDetail(BaseSimpleFormBean<Integer> formBean) {
		Integer acctid = formBean.getReqdata();
		if (acctid == null || acctid <= 0) return errorParamSmartResult();

		VerifyingMakerDto verifyingDetail = makerAccountMapper.getVerifyingDetail(acctid);
		return smartResult(verifyingDetail);
	}

	/**
	 * 实名审核个人账号
	 * state 0:通过 1:驳回
	 *
	 * @param formBean
	 * @return
	 */
	@Transactional
	public SmartResult verifyAccount(BaseSimpleFormBean<VerifyMakerFormBean> formBean) {
		VerifyMakerFormBean reqdata = formBean.getReqdata();
		if (reqdata == null || reqdata.getAcctid() <= 0) return errorParamSmartResult();

		int adminid = formBean.getUserid();
		int acctid = reqdata.getAcctid();
		int state = reqdata.getState();
		int usertype = reqdata.getUsertype();
		int bindcompid = reqdata.getBindcompid();
		String reason = reqdata.getReason();
		String remark = reqdata.getRemark();
		String customerManager = reqdata.getCustomerManager();
		int specialRateFlag = reqdata.getSpecialRateFlag();

		MakerAccount makerAccount = new MakerAccount().selectById(acctid);
		if (makerAccount == null) {
			return smartResult(StatusMsg.StatusMsg_201);
		} else if (makerAccount.getRealnameAuth() >= Constants.realname_auth_4) {
			return smartResult(StatusMsg.StatusMsg_203);
		}

		Integer userid = makerAccount.getUserid();
		MakerDetailDto makerDto = makerMapper.getUserDetail(userid);
		if (makerDto == null) return smartResult(StatusMsg.StatusMsg_201);
		int makerType = NumberUtil.safeInt(makerDto.getMakerType());

		Maker maker = new Maker().setUserid(userid);
		if (0 == reqdata.getState()) {
			if (makerType == MakerType.INTELL || makerType == MakerType.CROWDSOURCE) {
				MakerBankcard userBankcard = makerBankcardMapper.getDefaultBankcard(userid);
				if (null != userBankcard) {
					if (!userBankcard.getPayername().equals(makerAccount.getRealname())) {
						return smartResult(StatusMsg.StatusMsg_210);
					}
				}
			} else if (makerType == MakerType.TAXER) {
				//如果是 创客，判断支付有没有完成
				if (makerDto.getPaidState() != 2) {
					return smartResult(StatusMsg.StatusMsg_708);
				} else {
					//已付款, 开始生效日期
					maker.setIssueDate(new Date());
				}
			} else {
				//创客类型错误
				return smartResult(StatusMsg.StatusMsg_214);
			}
		}

		maker.setUsertype(usertype).setBindcompid(bindcompid).setSpecialRateFlag(specialRateFlag).updateById();
		int realnameAuth = state == 0 ? Constants.realname_auth_4 : Constants.realname_auth_3;

		// 审核通过
		if (realnameAuth == Constants.realname_auth_4) {
			//审核通过时 设置创客开户地
			if (0 == reqdata.getOpeningLocation()) {
				return smartResult(StatusMsg.StatusMsg_222);
			}
			makerAccount.setOpeningLocation(reqdata.getOpeningLocation());
			makerAccount.setAuthPassTime(new Date());
			makerAccount.setGongQingDetectionFailure(Constants.FALSE);
			makerAccount.setTemporaryLogin(reqdata.getTemporaryLogin());
		}

		makerAccount.setRealnameAuth(realnameAuth).setCustomerManager(customerManager).setAgreeProtocol(1);
		if (makerAccount.updateById()) {//取消ceo提醒通知审核超时
			ceoNoticeService.recordMakerVerify(userid, 1);

			//如果是审核通过，防止重复点击导致插入多条数据
			if (state == 0) {
				MakerAuthRecord record = new MakerAuthRecord().selectOne(
						Condition.create().eq("acctid", acctid).orderBy("id", false).last(" limit 1"));
				if (record != null && record.getState() == 0) {
					//上一条已经是审核通过的记录，那么就不需要再记录了。
					return smartResult();
				}
			}
			new MakerAuthRecord().setAdminid(adminid).setAcctid(acctid).setState(state).setReason(reason).setRemark(remark).insert();
			//结果通知创客
			if (makerDto.getMakerType() == MakerType.INTELL) {
				if (0 == state && 2 == reqdata.getOpeningLocation()) {
					//创客来源是  平台  and 审核通过 and 开户地是 共青城
					wxMessageService.examineMakerToBusinessInfoNotify(acctid, 3);
				} else {
					wxMessageService.userAuthState(acctid);
				}
			} else if (makerDto.getMakerType() == MakerType.CROWDSOURCE) {
				if (0 == state && 2 == reqdata.getOpeningLocation()) {
					//创客来源是 智众包平台  and 审核通过 and 开户地是 共青城
					wxCrowdsourceMessageService.examineMakerToGongQing(acctid);
				} else {
					wxCrowdsourceMessageService.crowdsourceAuthState(acctid);
				}
			} else if (makerDto.getMakerType() == MakerType.TAXER) {
				wxTaxerMessageService.userAuthState(acctid);
			}
		} else {
			return optFailSmartResult();
		}
		return smartResult();
	}

	/**
	 * 获取已实名的列表
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult getVerifyPassedList(BaseSimpleFormBean<MakerListFormBean> formBean) {
		MakerListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		Integer makerType = reqdata.getMakerType();
		if (makerType == null || makerType == 0) makerType = MakerType.INTELL;

		String name = reqdata.getName();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		String inviter = reqdata.getInviter();
		String bindcompname = reqdata.getBindcompname();
		String phone = reqdata.getPhone();
		Integer temporaryLogin = reqdata.getTemporaryLogin();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		Integer openingLocation = reqdata.getOpeningLocation();
		//添加筛选条件
		String dockingCity = conditionTemplate(formBean);
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<VerifyingMakerDto> list = makerAccountMapper.getVerifyList(makerType, name, inviter, 4, startDate, endDate, bindcompname,
				phone, openingLocation, dockingCity, temporaryLogin);
		//返回状态备注
		list.stream().forEach(dto -> {
			MakerStatusReason makerStatusReason = new MakerStatusReason().selectOne(Condition.create().eq("userid", dto.getUserid()));
			if (makerStatusReason != null)
				dto.setReason(makerStatusReason.getRealNameReason());
		});
		return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
	}

	/**
	 * 个人工作室开户
	 *
	 * @param formBean
	 * @return
	 */
	@Transactional
	public SmartResult createStudio(BaseSimpleFormBean<CreateStudioFormBean> formBean) {
		CreateStudioFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		int userid = reqdata.getUserid();
		String username = reqdata.getUsername();
		int tradecategoryid = reqdata.getTradecategoryid();
		String invoicescope = reqdata.getInvoicescope();

		if (StringUtil.isAnyEmpty(username, invoicescope) || NumberUtil.isAnyZero(userid, tradecategoryid)) {
			return errorParamSmartResult();
		}

		MakerDetailDto userDetail = getUserInfo(userid);
		if (userDetail == null) return smartResult(StatusMsg.StatusMsg_201);
		if (userDetail.getRealnameAuth() < Constants.realname_auth_4) return smartResult(StatusMsg.StatusMsg_202);
		if (userDetail.getStudioState() != 0) return smartResult(StatusMsg.StatusMsg_205);

		MakerAccount makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", reqdata.getUserid()));
		MakerStudio makerStudio =
				new MakerStudio().setState(StudioState.CREATING).setTaxAcctState(Constants.STUDIO_TAX_ACCT_NOT_QUALIFIED);
		BeanUtils.copyProperties(reqdata, makerStudio);
		//开通工作室后添加自我介绍
		if (!ObjectUtils.isEmpty(makerAccount)) {
			makerStudio.setIntro(makerAccount.getExpertIntro());
		}
		if (makerStudio.insertOrUpdate()) {
			new MakerAccount().setAcctid(userDetail.getAcctid()).setRealnameAuth(Constants.realname_auth_5).setWhetherAnExternalStudio(reqdata.getWhetherAnExternalStudio()).updateById();

			String bankname = reqdata.getBankname();
			String bankno = reqdata.getBankno();
			String acctno = reqdata.getAcctno();
			String openAcctBankName = reqdata.getOpenAcctBankName();
			String payername = reqdata.getPayername();
			String bankProvince = reqdata.getBankProvince();
			String bankCity = reqdata.getBankCity();

			int i = bindStudioBankcard(userid, bankname, bankno, openAcctBankName, acctno, payername, bankProvince, bankCity,
					Constants.BANK_ACCT_TYPE_COMPANY,null,0,null,false);
			if (i == -1) {
				return smartResult(StatusMsg.StatusMsg_211);
			} else if (i == -2) {
				return optFailSmartResult();
			} else if (i == -3){
				return smartResult(StatusMsg.BANKCARD_TYPE);
			}
//			boolean sendSuccess = sendOpenStudioNotice(userDetail, makerStudio.getUsername());
//			if (!sendSuccess) {
//				return optFailSmartResult();
//			}
			return smartResult();
		}
		return optFailSmartResult();
	}

	/**
	 * 创客开户时发送的消息通知
	 * @param makerDetailDto
	 * @param studioUserName 工作室名称
	 * @return
	 */
	public boolean sendOpenStudioNotice(MakerDetailDto makerDetailDto, String studioUserName) {
		//是否为临时登陆类型: 0:否 1:是
		int temporaryLogin = makerDetailDto.getTemporaryLogin();
		// 发微信通知给绑定企业、周雨辰;  发企业微信通知给商务经理
		if (temporaryLogin == 0) {
//			// 发送给芜湖的创客，提醒定税
//			if (NumberUtil.equals(makerDetailDto.getOpeningLocation(), 3)) {
//				if (NumberUtil.equals(makerDetailDto.getMakerType(), MakerType.INTELL)) {
//					wxMessageService.notifyWuhuMakerTaxVideo(makerDetailDto);
//				} else if (NumberUtil.equals(makerDetailDto.getMakerType(), MakerType.CROWDSOURCE)) {
//					wxCrowdsourceMessageService.notifyWuhuMakerTaxVideo(makerDetailDto);
//				}
//			}

			// 不是天津创客的,发微信通知给绑定企业、周雨辰;  发企业微信通知给商务经理
//			if (makerDetailDto.getOpeningLocation() != 1) {
				// 发送企业微信
				// ******公司的创客***，工商部门已审核通过，工作室名称为“*******“，预计3个工作日可下发执照，请提跟企业联系进行交易前的准备工作。
//				log.info("非天津创客开工作室消息,给企业/创客发消息，企业ID：" + makerDetailDto.getBindcompid());
////				boolean sendFlag = wxMessageService.sendNoticeToCompanyAndZhouYuchenForOpenAnAccount(makerDetailDto.getBindcompid(),
//						makerDetailDto.getRealname(), studioUserName);
//				if (!sendFlag) {
//					return false;
//				}
//
//				//通知商务经理
//				CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", makerDetailDto.getBindcompid()));
//				Company company = new Company().selectById(companyAccount.getCompid());
//				String info = company.getCompname() + "的创客" + makerDetailDto.getRealname() + "，工商部门已审核通过，工作室名称为“" + studioUserName +
//								"“，预计3个工作日可下发执照，请提跟企业联系进行交易前的准备工作。";
//				log.info("个人工作室开户发送商务经理信息：" + info);
//				//通知商务经理
//				new Thread(() -> commonService.sendEnterpriseWeChatNotice(companyAccount.getBusinessManagerId(), "", 1, info)).start();
//			}
		}
		return true;
	}

	/**
	 * 获取正在创建中的工作室列表
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult<StudioBriefDto> getVerifyingStudioList(BaseSimpleFormBean<MakerListFormBean> formBean) {
		MakerListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		Integer makerType = reqdata.getMakerType();
		if (makerType == null || makerType == 0) makerType = MakerType.INTELL;

		String name = reqdata.getName();
		Integer quotaFlag = reqdata.getQuotaFlag();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		String inviter = reqdata.getInviter();
		String bindcompname = reqdata.getBindcompname();
		Integer tradecategoryid = reqdata.getTradecategoryid();
		Integer temporaryLogin = reqdata.getTemporaryLogin();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		// 增加 根据注册地 进行筛选
		Integer openingLocation = reqdata.getOpeningLocation();
		//添加筛选条件
		String dockingCity = conditionTemplate(formBean);
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<StudioBriefDto> list = makerStudioMapper.getStudioList(makerType, 1, name, inviter, bindcompname, tradecategoryid, startDate,
				endDate, openingLocation, 0, addStudioDefaultRate(), dockingCity, temporaryLogin, null, quotaFlag,
				reqdata.getIsOpenAliPay(), reqdata.getMakerLabel(), reqdata.getIsOpenAccNo2(),null);
		//返回状态备注
		list.stream().forEach(dto -> {
			MakerStatusReason makerStatusReason = new MakerStatusReason().selectOne(Condition.create().eq("userid", dto.getUserid()));
			if (makerStatusReason != null)
				dto.setReason(makerStatusReason.getAccountOpeningReason());
		});
		return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
	}

	/**
	 * 确认工作室开户完成
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult confirmStudio(BaseSimpleFormBean<ConfirmStudioFormBean> formBean) {
		ConfirmStudioFormBean reqdata = formBean.getReqdata();

		if (reqdata == null || reqdata.getUserid() <= 0 || StringUtil.isEmpty(reqdata.getStudiolicensephoto()))
			return errorParamSmartResult();

		int userid = reqdata.getUserid();

		MakerDetailDto userDetail = getUserInfo(userid);
		if (userDetail == null) return smartResult(StatusMsg.StatusMsg_201);
		if (userDetail.getRealnameAuth() < Constants.realname_auth_4) return smartResult(StatusMsg.StatusMsg_202);
		if (userDetail.getStudioState() == 0) return smartResult(StatusMsg.StatusMsg_204);

		MakerStudio makerStudio = new MakerStudio();
		BeanUtils.copyProperties(reqdata, makerStudio);
		makerStudio.setState(StudioState.CONFIRMED).setOpenAdminid(formBean.getUserid()).setOpenFinishtime(new Date());

		if (makerStudio.updateById()) {
			new MakerAccount().setAcctid(userDetail.getAcctid()).setRealnameAuth(Constants.realname_auth_5).updateById();
			if (userDetail.getMakerType() == MakerType.INTELL) {
				wxMessageService.userStudioConfirmed(userid);
			} else if (userDetail.getMakerType() == MakerType.CROWDSOURCE) {
				wxCrowdsourceMessageService.userStudioConfirmed(userid);
			} else if (userDetail.getMakerType() == MakerType.TAXER) {
				wxTaxerMessageService.userStudioConfirmed(userid);
			}
			return smartResult();
		}
		return optFailSmartResult();
	}

	/**
	 * 获取已开户完成的工作室列表
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult<StudioBriefDto> getComfirmedStudioList(BaseSimpleFormBean<MakerListFormBean> formBean) {
		MakerListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		Integer makerType = reqdata.getMakerType();
		if (makerType == null || makerType == 0) makerType = MakerType.INTELL;
		Integer changedDefaultRate = reqdata.getChangedDefaultRate();
		if (changedDefaultRate == null) {
			changedDefaultRate = 0;
		}

		Integer quotaFlag = reqdata.getQuotaFlag();
		String name = reqdata.getName();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		String inviter = reqdata.getInviter();
		String bindcompname = reqdata.getBindcompname();
		Integer tradecategoryid = reqdata.getTradecategoryid();
		Integer isOpenAliPay = reqdata.getIsOpenAliPay();
		Integer isOpenAccNo2 = reqdata.getIsOpenAccNo2();
		String makerLabel = StringUtil.isEmpty(reqdata.getMakerLabel()) ? null : reqdata.getMakerLabel();
		Integer expertLabelState = reqdata.getExpertLabelState();
		// 增加 根据注册地 进行筛选
		Integer openingLocation = reqdata.getOpeningLocation();
		Integer temporaryLogin = reqdata.getTemporaryLogin();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();
		//添加筛选条件
		String dockingCity = conditionTemplate(formBean);
		Page<StudioBriefDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<StudioBriefDto> list = makerStudioMapper.getStudioList(makerType, 2, name, inviter, bindcompname, tradecategoryid, startDate, endDate, openingLocation,
				changedDefaultRate, addStudioDefaultRate(), dockingCity, temporaryLogin, expertLabelState, quotaFlag, isOpenAliPay,
				makerLabel, isOpenAccNo2,formBean.getReqdata().getWhetherAnExternalStudio());
		for (StudioBriefDto studio:list){
			CrowdsourceAccount crowdsourceAccount = makerStudioMapper.getNaturalPersonStatus(studio.getIdno());
			if (crowdsourceAccount == null){
				studio.setNaturalPersonStatus(0);
			}else {
				studio.setNaturalPersonStatus(1);
			}
			//返回状态备注
			MakerStatusReason makerStatusReason = new MakerStatusReason().selectOne(Condition.create().eq("userid", studio.getUserid()));
			if (makerStatusReason != null)
				studio.setReason(makerStatusReason.getOpenedReason());
		}
	/*	for (StudioBriefDto studio : page) {
			studio.setChangedDefaultRate(checkStudioDefaultRate(studio));
		}*/
		return smartResultPage(page);
	}

	//设置创客标签
	@Transactional
	public SmartResult saveMakerAccountLabel(BaseSimpleFormBean<MakerLabelFormBean> formBean) {
		MakerLabelFormBean makerAlipayLabel = formBean.getReqdata();

		List<String> labelList = makerAlipayLabel.getMakerLabelList();
		String labels = StringUtils.join(labelList.toArray(), ",");

		String useridStr = makerAlipayLabel.getUserid();
		List<String> userIdlist = new ArrayList(Arrays.asList(useridStr.split(",")));
		for (String userid : userIdlist) {
			//检验数据存在
			MakerAccount makerAccount = makerAccountMapper.getUserAccountByUserId(Integer.parseInt(userid));
			if (makerAccount == null) {
				return SmartResult.fail(StatusMsg.StatusMsg_201);
			}
			//修改标签
			makerAccount.setMakerLabel(labels);
			makerAccount.updateById();
		}
		return SmartResult.success();
	}

	/**
	 * 获取工作室详情
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult getStudioDetail(BaseSimpleFormBean<Integer> formBean) {
		Integer userid = formBean.getReqdata();

		StudioDetailDto studioDetail = makerStudioMapper.getStudioDetail(userid);
		return smartResult(studioDetail);
	}

	private String addStudioDefaultRate() {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("IF(")
				.append(" us.gen_low_service_rate=")
				.append(commonConfig.getGenLowServiceRate())
				.append(" and us.gen_high_service_rate=")
				.append(commonConfig.getGenHighServiceRate())
				.append(" and us.gen_high_tax_rate=")
				.append(commonConfig.getGenHighTaxRate())
				.append(" and us.spe_service_rate=")
				.append(commonConfig.getSpeServiceRate())
				.append(" and us.spe_tax_rate=")
				.append(commonConfig.getSpeTaxRate())
				.append(" and us.yearly_high_tax_rate=")
				.append(commonConfig.getYearlyHighTaxRate())
				.append(" and us.yearly_high_service_rate=")
				.append(commonConfig.getYearlyHighServiceRate())
				.append(" and us.yearly_high_2_tax_rate=")
				.append(commonConfig.getYearlyHigh2TaxRate())
				.append(" and us.yearly_high_2_service_rate=")
				.append(commonConfig.getYearlyHigh2ServiceRate())
				.append(",0,1) as changedDefaultRate");
		return stringBuilder.toString();
	}

	private int checkStudioDefaultRate(StudioBriefDto studio) {
		int changed = 0;
		if (!studio.getGenLowServiceRate().equals(commonConfig.getGenLowServiceRate())) changed = 1;
		if (changed == 1) return changed;

		if (!studio.getGenHighServiceRate().equals(commonConfig.getGenHighServiceRate())) changed = 1;
		if (changed == 1) return changed;

		if (!studio.getGenHighTaxRate().equals(commonConfig.getGenHighTaxRate())) changed = 1;
		if (changed == 1) return changed;

		if (!studio.getSpeServiceRate().equals(commonConfig.getSpeServiceRate())) changed = 1;
		if (changed == 1) return changed;

		if (!studio.getSpeTaxRate().equals(commonConfig.getSpeTaxRate())) changed = 1;
		if (changed == 1) return changed;

		if (!studio.getYearlyHighServiceRate().equals(commonConfig.getYearlyHighServiceRate())) changed = 1;
		if (changed == 1) return changed;

		if (!studio.getYearlyHighTaxRate().equals(commonConfig.getYearlyHighTaxRate())) changed = 1;
		if (changed == 1) return changed;

		if (!studio.getYearlyHigh2ServiceRate().equals(commonConfig.getYearlyHigh2ServiceRate())) changed = 1;
		if (changed == 1) return changed;

		if (!studio.getYearlyHigh2TaxRate().equals(commonConfig.getYearlyHigh2TaxRate())) changed = 1;
		if (changed == 1) return changed;

		if (!studio.getYearlyHigh3ServiceRate().equals(commonConfig.getYearlyHigh3ServiceRate())) changed = 1;
		if (changed == 1) return changed;

		if (!studio.getYearlyHigh3TaxRate().equals(commonConfig.getYearlyHigh3TaxRate())) changed = 1;
		if (changed == 1) return changed;

		return changed;
	}

	/**
	 * 编辑工作室详情
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult editStudio(BaseSimpleFormBean<EditStudioFormBean> formBean) {
		EditStudioFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		Integer userid = reqdata.getUserid();
		Maker maker = new Maker().selectById(userid);
		maker.setUserid(userid)
				.setUsertype(reqdata.getUsertype())
				.setBindcompid(reqdata.getBindcompid())
				.setNoticeFlag(reqdata.getNoticeFlag())
				.setCustodianId(reqdata.getCustodianId())
				.setPlatformHosting(reqdata.getPlatformHosting());

		MakerStudio makerStudio = new MakerStudio();
		BeanUtils.copyProperties(reqdata, makerStudio);

		// 设置固定费率
		if (NumberUtil.equals(makerStudio.getFixedService(), Constants.TRUE)) {
			Double fixedServiceRate = makerStudio.getFixedServiceRate();
			double taxRate = 0d;

			makerStudio.setSpeServiceRate(fixedServiceRate)
					.setGenLowServiceRate(fixedServiceRate)
					.setGenHighServiceRate(fixedServiceRate)
					.setYearlyHighServiceRate(fixedServiceRate)
					.setYearlyHigh2ServiceRate(fixedServiceRate)
					.setYearlyHigh3ServiceRate(fixedServiceRate)
					.setSpeTaxRate(taxRate)
					.setGenHighTaxRate(taxRate)
					.setYearlyHighTaxRate(taxRate)
					.setYearlyHigh2TaxRate(taxRate)
					.setYearlyHigh3TaxRate(taxRate);
		}

		MakerAccount makerAccount = new MakerAccount();
		BeanUtils.copyProperties(reqdata, makerAccount);

		maker.updateById();
		makerAccount.update(Condition.create().eq("userid", userid));
		makerStudio.updateById();

		if (maker.getMakerType() == MakerType.INTELL || maker.getMakerType() == MakerType.CROWDSOURCE || maker.getMakerType() == MakerType.TAXER) {
			//绑定个人账户
			int i = bindStudioBankcard(userid, reqdata.getBankname(), "", reqdata.getOpenAcctBankName2(), reqdata.getAcctno(),
					reqdata.getPayername(), reqdata.getBankProvince2(), reqdata.getBankCity2(), Constants.BANK_ACCT_TYPE_PERSONAL,reqdata.getAlipayAccount(),reqdata.getPaymentAccountStatus(),reqdata.getTelephone(),false);
			if (i == -1) {
				return smartResult(StatusMsg.StatusMsg_211);
			} else if (i == -2) {
				return optFailSmartResult();
			} else if (i == -3){
				return smartResult(StatusMsg.BANKCARD_TYPE);
			}

			//绑定对公账户
			int i1 = bindStudioBankcard(userid, reqdata.getBankname2(), reqdata.getBankno2(), reqdata.getOpenAcctBankName2(),
					reqdata.getAcctno2(), reqdata.getPayername2(), reqdata.getBankProvince2(), reqdata.getBankCity2(),
					Constants.BANK_ACCT_TYPE_COMPANY,null,reqdata.getPaymentAccountStatus(),null,false);
			if (i1 == -1) {
				return smartResult(StatusMsg.StatusMsg_211);
			} else if (i1 == -2) {
				return optFailSmartResult();
			} else if (i == -3){
				return smartResult(StatusMsg.BANKCARD_TYPE);
			}
		}

		return smartResult();
	}

	/**
	 * 绑定银行卡信息,创客可绑定个人账户和对公账户
	 *
	 * @return -2: 绑定失败 -1：账户信息不全 0：不需要绑定 1：绑定成功  -3卡类型不是储蓄卡
	 */
	private int bindStudioBankcard(int userid, String bankname, String bankno, String openAcctBankName, String acctno, String payername,
	                               String bankProvince, String bankCity, int accttype,String alipayAccount,Integer paymentAccountStatus,String telephone,boolean whetherToVerify) {
		if (accttype <= 0 || accttype > 2) {
			return -1;
		}

		if (StringUtil.isAllEmpty(bankname, bankno, acctno, payername)) {
			//信息都没有，不绑定
			return 0;
		} else {
			//账户信息校验
			if (StringUtil.isAnyEmpty(bankname, acctno, payername)) {
				return -1;
			}
			JSONObject jsonObject = new JSONObject();
			if(accttype == 1) {
				if (whetherToVerify) {
					jsonObject = bankCardElementCertificationService.homeQuery(acctno);
					if (!BankCardElementCertificationService.TYPE.equals(jsonObject.getString("type"))) {
						return -3;
					}
				}
			}
			//现将其他已经绑了的银行卡置为失效
			new MakerBankcard().setState(2).update(Condition.create().eq("userid", userid).eq("accttype", accttype));
			//检查是否存在这张卡
			MakerBankcard bankcard = new MakerBankcard().selectOne(Condition.create().eq("userid", userid).eq("acctno", acctno));
			if (bankcard != null) {
				bankcard.setState(1);
			} else {
				bankcard = new MakerBankcard().setUserid(userid).setAccttype(accttype).setState(1);
			}

			bankcard.setBankname(bankname)
					.setBankno(bankno)
					.setAcctno(acctno)
					.setPayername(payername);
			if (!jsonObject.isEmpty()) {
				bankcard.setCardName(jsonObject.getString("cardName"))
						.setProvince(jsonObject.getString("province"))
						.setCity(jsonObject.getString("city"));
			}
			if (StringUtils.isNotBlank(openAcctBankName)) {
				bankcard.setOpenAcctBankName(openAcctBankName);
			}
			if (StringUtils.isNotBlank(alipayAccount)){
				bankcard.setAlipayAccount(alipayAccount);
			}
			if (StringUtils.isNotBlank(telephone)){
				bankcard.setTelephone(telephone);
			}
			if (null != paymentAccountStatus){
				bankcard.setPaymentAccountStatus(paymentAccountStatus);
			}
			if (bankcard.insertOrUpdate()) {
				return 1;
			}
		}

		return -2;
	}

	/**
	 * 删除未提交审核的创客（一般是注册错误了的用户）
	 */
	public SmartResult delUser(BaseSimpleFormBean<Integer> formBean) {
		Integer userid = formBean.getReqdata();
		int count = new CompanyProject().selectCount(Condition.create().eq("userid", userid));
		if (count == 0) {
			makerMapper.deleteUser(userid);
		}
		return smartResult();
	}

	/**
	 * 直接创建创客账户，提交实名审核
	 */
	public SmartResult createAccount(BaseSimpleFormBean<CreateAccountFormBean> formBean) {
		SmartResult smartResult = new SmartResult();

		CreateAccountFormBean reqdata = formBean.getReqdata();

		if (null == reqdata) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		int userid = reqdata.getUserid();
		Maker maker = new Maker().selectById(userid);
		if (null == maker) {
			//新增
			maker = new Maker();
			maker.setState(Constants.user_state_2)
					.setCompremark(reqdata.getCompremark())
					.setPhone(reqdata.getRegisteredPhone())
					.setCompremark(reqdata.getCompremark())
					.setHasCompany(reqdata.getHasCompany())
					.setHasContract(reqdata.getHasContract())
					.setWorkComapny(reqdata.getWorkCompany())
					.setMakerType(reqdata.getMakerType())
					.insert();
		} else {
			//修改
			maker.setCompremark(reqdata.getCompremark())
					.setPhone(reqdata.getRegisteredPhone())
					.setHasCompany(reqdata.getHasCompany())
					.setHasContract(reqdata.getHasContract())
					.setWorkComapny(reqdata.getWorkCompany())
					.setMakerType(reqdata.getMakerType())
					.updateById();
		}

		MakerAccount makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", maker.getUserid()));

		if (null == makerAccount) {
			//第一次提交 新增
			makerAccount = new MakerAccount().setRealnameAuth(Constants.realname_auth_2);
			BeanUtils.copyProperties(reqdata, makerAccount);
			makerAccount.setUserid(maker.getUserid()).setAuthSubmitTime(new Date()).insert();
		} else {
			//重新提交资料
			BeanUtils.copyProperties(reqdata, makerAccount);
			//编辑时 判断创客状态，如果<4的话，realname_auth=2，>=4的话不改变当前状态
			if (maker.getState() < 4) {
				makerAccount.setRealnameAuth(Constants.realname_auth_2);
			}
			if (makerAccount.getAuthSubmitTime() == null) {
				makerAccount.setAuthSubmitTime(new Date());
			}
			makerAccount.updateById();
		}

		int i = bindStudioBankcard(maker.getUserid(), reqdata.getBankname(), "", reqdata.getOpenAcctBankName(), reqdata.getAcctno(), reqdata.getPayername(), "", "",
				Constants.BANK_ACCT_TYPE_PERSONAL,reqdata.getAlipayAccount(),reqdata.getPaymentAccountStatus(),reqdata.getTelephone(),false);
		if (i == -1) {
			return smartResult(StatusMsg.StatusMsg_211);
		} else if (i == -2) {
			return optFailSmartResult();
		}else if (i == -3){
			return smartResult(StatusMsg.BANKCARD_TYPE);
		}

		return smartResult;
	}

	public SmartResult changeAccountState(BaseSimpleFormBean<ChangeAccountStateFormBean> formBean) {
		ChangeAccountStateFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		boolean update = new MakerAccount().setRealnameAuth(reqdata.getState()).update(Condition.create().eq("userid",
				reqdata.getState()));
		if (update) return smartResult();
		return optFailSmartResult();
	}

	public SmartResult editRealNameInfo(BaseSimpleFormBean<EditRealNameFormBean> formBean) {
		EditRealNameFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		MakerAccount makerAccount = new MakerAccount();
		BeanUtils.copyProperties(reqdata, makerAccount);

		makerAccount.setRealnameAuth(Constants.realname_auth_2).update(Condition.create().eq("userid", reqdata.getUserid()));

		Maker maker = new Maker();
		BeanUtils.copyProperties(reqdata, maker);
		maker.updateById();

		return smartResult();
	}

	public SmartResult addDefaultTag(BaseSimpleFormBean<String> formBean) {
		String tagname = formBean.getReqdata();
		if (StringUtil.isEmpty(tagname)) return errorParamSmartResult();

		Tag tag = new Tag().selectOne(Condition.create().eq("tagname", tagname));
		if (tag != null) {
			if (tag.getType() == Constants.TAG_DEFAULT) {
				return smartResult(StatusMsg.StatusMsg_208);
			} else {
				tag.setType(Constants.TAG_DEFAULT).updateById();
				return smartResult(tag.getTagid());
			}
		}

		tag = new Tag().setTagname(tagname).setType(Constants.TAG_DEFAULT);
		if (tag.insert()) return smartResult(tag.getTagid());

		return optFailSmartResult();
	}

	public SmartResult getDefaultTagList(BaseSimpleFormBean formBean) {
		List<Tag> list = new Tag().selectList(Condition.create().eq("type", Constants.TAG_DEFAULT));
		return smartResult(list);
	}

	public SmartResult delDefaultTag(BaseSimpleFormBean<Integer> formBean) {
		Integer tagid = formBean.getReqdata();
		new Tag().delete(Condition.create().eq("tagid", tagid));
		new MakerTag().delete(Condition.create().eq("tagid", tagid));
		return smartResult();
	}

	public SmartResult editInviteCode(BaseSimpleFormBean<EditInviteCodeFormBean> formBean) {
		EditInviteCodeFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		int userid = reqdata.getUserid();
		String inviteCode = reqdata.getInviteCode();

		new Maker().setUserid(userid).setInviteCode(inviteCode).updateById();
		return smartResult();
	}

	public SmartResult changeNoticeFlag(BaseSimpleFormBean<ChangeNoticeFlagFormBean> formBean) {
		ChangeNoticeFlagFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		int idtype = reqdata.getIdtype();
		int userid = reqdata.getUserid();
		int noticeFlag = reqdata.getNoticeFlag();
		if (NumberUtil.isAnyZero(idtype, userid) || (noticeFlag != 0 && noticeFlag != 1)) return errorParamSmartResult();

		switch (idtype) {
			case UserType.MAKER:
				new Maker().setUserid(userid).setNoticeFlag(noticeFlag).updateById();
				break;
			case UserType.COMPANY:
				new Company().setCompid(userid).setNoticeFlag(noticeFlag).updateById();
				break;
			case UserType.PARTNER:
				new Partner().setPartnerid(userid).setNoticeFlag(noticeFlag).updateById();
				break;
			default:
				break;
		}
		return smartResult();
	}

	public SmartResult openTaxAcct(BaseSimpleFormBean<OpenTaxAcctFormBean> formBean) {
		OpenTaxAcctFormBean reqdata = formBean.getReqdata();
		int state = reqdata.getState();
		String[] arr = reqdata.getUserids().split(",");
		for (int i = 0; i < arr.length; i++) {
			Integer userid = StringUtil.toInt(arr[i]);
			if (state == 1) { //开始开户
				//手动设置开税户流程开始，ceo通知
				ceoNoticeService.recordMakerOpenTaxAcct(userid, 0);
			} else if (state == 2) { //开户完成
				new MakerStudio().setUserid(userid)
						.setTaxAcctState(Constants.STUDIO_TAX_ACCT_CONFIRMED)
						.setOpenTaxAcct(1)
						.setOpenTaxAcctAdminid(formBean.getUserid())
						.setOpenTaxAcctFinishtime(new Date())
						.updateById();
				ceoNoticeService.recordMakerOpenTaxAcct(userid, 1);

				invoiceInventoryService.oepnTaxAcctFirstInventoryIn(userid, formBean.getUserid());
				MakerDetailDto userDetail = makerMapper.getUserDetail(userid);
				// 天津地区创客,开税户后通知企业和商务经理
				if (userDetail.getOpeningLocation() == 1) {
					// 给企业发通知
					Company company = new Company().selectById(userDetail.getBindcompid());
					if(company != null) {
						CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", company.getCompid()));
						wxMessageService.notifyCompanyMakerOpenTax(company, userDetail);

						String info = String.format("%s公司的创客%s，已开天津税户，工作室名称为“%s“，请提跟企业联系进行交易准备工作。", company.getCompname(),
								userDetail.getRealname(), userDetail.getUsername());
						log.info("开税户发送给商务经理的信息：" + info);
						new Thread(() -> commonService.sendEnterpriseWeChatNotice(companyAccount.getBusinessManagerId(), "", 1, info)).start();
					}
				}
			}
		}
		return smartResult();
	}

	public SmartResult finishTax(BaseSimpleFormBean<FinishTaxFromBean> formBean)  {
		FinishTaxFromBean reqdata = formBean.getReqdata();
		int managerid = formBean.getUserid();
		String year = reqdata.getYear();
		int quarter = reqdata.getQuarter();
		String userids = reqdata.getUserids();
		//获取该季度的最后一个月最后一天
		String date = DateUtil.getStrings(DateUtil.getLastDayOfQuarter(StringUtil.toInt(year),quarter));

		List<String> useridList;
		if (StringUtil.isEmpty(userids)) {
			useridList = makerStudioMapper.getAllOpenTaxAcctIds();
		} else {
			useridList = Lists.newArrayList(userids.split(","));
		}
		for (String id : useridList){
			List<MakerFinishTax> makerFinishTax = new MakerFinishTax()
					.selectList(Condition.create()
							.eq("userid", id)
							.eq("year",year)
							.eq("quarter",quarter));
			if (makerFinishTax.size() <= 0) {
				//获取创客完成开户日期
				String makerStudio = makerStudioMapper.getDate(id);
				if (makerStudio != null) {
					try {
						if (DateUtil.compareToTime(makerStudio, date)) {
							new MakerFinishTax().setUserid(StringUtil.toInt(id))
									.setYear(year)
									.setQuarter(quarter)
									.setManagerid(managerid)
									.insert();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

		return smartResult();
	}

	/**
	 * 获取已开户完成的工作室列表
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult<StudioBriefDto> getOpenTaxAcctList(BaseSimpleFormBean<MakerListFormBean> formBean) {
		MakerListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		Integer makerType = reqdata.getMakerType();
		if (makerType == null || makerType == 0) makerType = MakerType.INTELL;
		Integer changedDefaultRate = reqdata.getChangedDefaultRate();
		if (changedDefaultRate == null) {
			changedDefaultRate = 0;
		}
		String name = reqdata.getName();
		Integer quotaFlag = reqdata.getQuotaFlag();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		String inviter = reqdata.getInviter();
		String bindcompname = reqdata.getBindcompname();
		Integer expertLabelState = reqdata.getExpertLabelState();
		Integer isOpenAliPay = reqdata.getIsOpenAliPay();
		Integer isOpenAccNo2 = reqdata.getIsOpenAccNo2();
		String makerLabel = StringUtil.isEmpty(reqdata.getMakerLabel()) ? null : reqdata.getMakerLabel();
		Integer tradecategoryid = reqdata.getTradecategoryid();
		int taxAcctState = reqdata.getTaxAcctState();
		Integer temporaryLogin = reqdata.getTemporaryLogin();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		Integer openingLocation = reqdata.getOpeningLocation();
		//添加筛选条件
		String dockingCity = conditionTemplate(formBean);
		Page<StudioBriefDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		makerStudioMapper.getOpenTaxAcctStudioList(taxAcctState, makerType, name, inviter, bindcompname, tradecategoryid, startDate,
				endDate, openingLocation, changedDefaultRate, addStudioDefaultRate(), dockingCity, temporaryLogin, expertLabelState,
				quotaFlag, isOpenAliPay, makerLabel, isOpenAccNo2,reqdata.getWhetherAnExternalStudio());
	/*	for (StudioBriefDto studio : page) {
			studio.setChangedDefaultRate(checkStudioDefaultRate(studio));
		}*/
		return smartResultPage(page);
	}

	public void downloadStudioTaxAcctList(HttpServletResponse response, MakerListFormBean reqdata) {

		Integer makerType = reqdata.getMakerType();
		if (makerType == null || makerType == 0) makerType = MakerType.INTELL;

		String name = reqdata.getName();
		Integer quotaFlag = reqdata.getQuotaFlag();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		String inviter = reqdata.getInviter();
		String bindcompname = reqdata.getBindcompname();
		Integer tradecategoryid = reqdata.getTradecategoryid();
		int taxAcctState = reqdata.getTaxAcctState();
		Integer temporaryLogin = reqdata.getTemporaryLogin();
		Integer isOpenAliPay = reqdata.getIsOpenAliPay();
		Integer isOpenAccNo2 = reqdata.getIsOpenAccNo2();
		String makerLabel = StringUtil.isEmpty(reqdata.getMakerLabel()) ? null : reqdata.getMakerLabel();

		if (startDate == null) {
			startDate = new Date(0);
		}
		if (endDate == null) {
			endDate = new Date();
		}
		if (bindcompname == null) {
			bindcompname = "";
		}

		Integer openingLocation = reqdata.getOpeningLocation();

		List<StudioBriefExportDto> list = makerStudioMapper.getOpenTaxAcctStudioList(taxAcctState, makerType, name, inviter, bindcompname,
				tradecategoryid, startDate, endDate, openingLocation, 0, addStudioDefaultRate(), "", temporaryLogin, null, quotaFlag,
				isOpenAliPay, makerLabel, isOpenAccNo2,null).stream().map(StudioBriefExportDto::of).collect(Collectors.toList());

		String file = RandomUtil.createRandomNo("工作室列表_", "");
		try {
			EasyExcel.write(getExcelOutPutStream(response, file), StudioBriefExportDto.class).sheet("工作室").doWrite(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public SmartResult makerRescission(BaseSimpleFormBean<Integer> formBean) {
		Integer userid = formBean.getReqdata();
		Maker maker = new Maker().selectById(userid);
		MakerAccount makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", userid));
		if (null == maker || null == makerAccount) {
			return smartResult(StatusMsg.StatusMsg_201);
		}
		//判断是否有待开票
		if (this.checkWhetherPass(new MakerRescissionApply().setUserid(userid))) {
			return smartResult(StatusMsg.StatusMsg_229);
		}
		maker.setState(Constants.user_state_4).setPhone(maker.getPhone() + "off").setLogouttime(new Date()).setLogoutOperator(formBean.getUserid());
		makerAccount.setIdno(makerAccount.getIdno() + "off");

		if (maker.updateById() && makerAccount.updateById()) {
			return smartResult();
		} else {
			return smartResult(StatusMsg.StatusMsg_199);
		}
	}

	/**
	 * 获取已解约工作室列表
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult<StudioBriefDto> getRescissionList(BaseSimpleFormBean<MakerListFormBean> formBean) {
		MakerListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		Integer makerType = reqdata.getMakerType();
		if (makerType == null || makerType == 0) makerType = MakerType.INTELL;

		String name = reqdata.getName();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		String inviter = reqdata.getInviter();
		String bindcompname = reqdata.getBindcompname();
		Integer tradecategoryid = reqdata.getTradecategoryid();
		int taxAcctState = reqdata.getTaxAcctState();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();
		//添加筛选条件
		String dockingCity = conditionTemplate(formBean);
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<StudioBriefDto> list = makerStudioMapper.getRescissionList(taxAcctState, makerType, name, inviter, bindcompname,
				tradecategoryid, startDate, endDate, dockingCity);
		return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
	}

	public SmartResult uploadCancellationBook(BaseSimpleFormBean<UploadCancellationBookFormBean> formBean) {
		MakerStudio makerStudio = new MakerStudio().selectById(formBean.getReqdata().getUserid());
		Asserts.notNull(makerStudio);
		Asserts.isTrue(makerStudio.setCancellationBook(formBean.getReqdata().getCancellationBook()).updateById());

		return smartResult();
	}

	public SmartResult<MakerRescissionApplyDto> getRescissionApplyList(BaseSimpleFormBean<RescissionApplyListFormBean> formBean) {
		@Valid RescissionApplyListFormBean reqdata = formBean.getReqdata();
		String name = reqdata.getName();
		List<Integer> stateList = reqdata.getStates();
		String states = "0";
		if (!CollectionUtils.isEmpty(stateList)) {
			states = stateList.stream().map(String::valueOf).collect(Collectors.joining(","));
		}
		//添加筛选条件
		String dockingCity = conditionTemplate(formBean);
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<MakerRescissionApplyDto> list = makerRescissionApplyMapper.getApplyList(name, states, dockingCity);
		for (MakerRescissionApplyDto makerRescissionApplyDto : list) {
			// 设置主体
			if(makerRescissionApplyDto.getIntelCrowdsource() == 2){
				CompanyParty companyParty = coreCompanyService.getCompanyDefaultPartyCro(makerRescissionApplyDto.getBindcompid());
				makerRescissionApplyDto.setCroPartyId(companyParty == null ? 0 : companyParty.getPartyId());
			}
			// 当前年发单金额
			BigDecimal yearProjectAmount = companyProjectMapper.getProjectAmountByUseridAllCompany(makerRescissionApplyDto.getUserid(), 1);
			// 累计发单金额
			BigDecimal allProjectAmount = companyProjectMapper.getProjectAmountByUseridAllCompany(makerRescissionApplyDto.getUserid(), 0);
			//智众包当前年发单金额
			BigDecimal yearCrowdSourceProjectAmount = crowdsourceTradeRecordMapper.getCrowdSourceProjectAmountByUseridAllCompany(
					makerRescissionApplyDto.getUserid(), 1);
			//智众包累计发单金额
			BigDecimal allCrowdSourceProjectAmount = crowdsourceTradeRecordMapper.getCrowdSourceProjectAmountByUseridAllCompany(
					makerRescissionApplyDto.getUserid(), 0);
			//赋值进dto
			makerRescissionApplyDto.setCurrentYearAmount(yearProjectAmount.add(yearCrowdSourceProjectAmount))
					.setAccumulatedAmount(allProjectAmount.add(allCrowdSourceProjectAmount));
		}
		return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
	}

	public SmartResult handleRescissionApply(BaseSimpleFormBean<HandleRescissionApplyFormBean> formBean) {
		@Valid HandleRescissionApplyFormBean reqdata = formBean.getReqdata();
		MakerRescissionApply apply = new MakerRescissionApply().selectById(reqdata.getId());
		if (apply == null) return smartResult(StatusMsg.StatusMsg_215);

		Integer userid = apply.getUserid();
		//状态  2：已受理 3：已拒绝 4：已完成解约
		int state = reqdata.getState();
		if (state == 2 || state == 3) {
			if (2 == state) {
				//注销申请点通过的时候，要判断该创客是否还有发票没开完，有的话不能注销
				if (checkWhetherPass(apply)) {
					return smartResult(StatusMsg.StatusMsg_229);
				}
			}
			apply.setHandletime(new Date()).setHandleAdminid(formBean.getUserid());
		} else if (state == 4) {
			apply.setFinishtime(new Date()).setFinishAdminid(formBean.getUserid());
		}
		boolean update = apply.setState(state).setRemark(reqdata.getRemark()).updateById();

		if (update) {

			if (state == 4) {
				new Maker().setUserid(userid).setState(Constants.user_state_4).setLogouttime(new Date()).updateById();
			}

			//发送微信模板消息
			try {
				wxMessageService.nofityMakerRescissionApply(apply);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return smartResult();
		}
		return optFailSmartResult();
	}

	/**
	 * 创建注销申请
	 * @param formBean
	 * @return
	 */
	public SmartResult createRescissionApply(BaseSimpleFormBean<CreateRescissionApplyFormBean> formBean) {
		@Valid CreateRescissionApplyFormBean req = formBean.getReqdata();
		MakerRescissionApply apply = new MakerRescissionApply();
		apply.setUserid(req.getUserid())
			 .setReason(req.getReason())
			 .setState(1)
			 .setCreater(formBean.getUserid())
			 .setCreateType(2)
			 .insert();

		return SmartResult.success();
	}

	/**
	 * 提交注销申请
	 * @param formBean
	 * @return
	 */
	public SmartResult submitRescissionApply(BaseSimpleFormBean<SubmitRescissionApplyFormBean> formBean) {
		@Valid SubmitRescissionApplyFormBean req = formBean.getReqdata();
		MakerRescissionApply apply = new MakerRescissionApply().selectById(req.getId());
		Asserts.notNull(apply, StatusMsg.StatusMsg_215);
		// 状态错误禁止提交
		if (apply.getState() != 1) {
			return smartResult(StatusMsg.StatusMsg_141);
		}
		// 提交
		apply.setState(5)
			 .setAdvise(req.getAdvise())
			 .updateById();

		// TODO 发消息给胡总(消息带连接)

		return SmartResult.success();
	}

	/**
	 * CEO处理提交注销申请
	 * @param formBean
	 * @return
	 */
	public SmartResult processRescissionApply(BaseSimpleFormBean<ProcessRescissionApplyFormBean> formBean) {
		ProcessRescissionApplyFormBean req = formBean.getReqdata();

		int userid = formBean.getUserid();
		int idtype = formBean.getIdtype();
		if (!NumberUtil.intIn(idtype, UserType.MAKER, UserType.MAKER_CROWDSOURCE)) return smartResult(StatusMsg.StatusMsg_214);

		List<Integer> idList = req.getIdList();
		for (Integer id:idList){
			MakerRescissionApply apply = new MakerRescissionApply().selectById(id);
			Asserts.notNull(apply, StatusMsg.StatusMsg_215);
			apply.setState(req.getState()).setRemark(req.getRemark()).updateById();
		}
		// TODO 发消息给客服
		return smartResult();
	}

	//注销同步未满10万
	public SmartResult logOutOfSync(HandleRescissionApplyFormBean formBean,Integer userId) {
		@Valid HandleRescissionApplyFormBean reqdata = formBean;
		MakerRescissionApply apply = new MakerRescissionApply().selectById(reqdata.getId());
		if (apply == null) return smartResult(StatusMsg.StatusMsg_215);

		Integer userid = apply.getUserid();
		//状态  2：已受理 3：已拒绝 4：已完成解约
		int state = reqdata.getState();
		if (state == 2 || state == 3) {
			if (2 == state) {
				//注销申请点通过的时候，要判断该创客是否还有发票没开完，有的话不能注销
				if (checkWhetherPass(apply)) {
					return smartResult(StatusMsg.StatusMsg_229);
				}
			}
			apply.setHandletime(new Date()).setHandleAdminid(userId);
		} else if (state == 4) {
			apply.setFinishtime(new Date()).setFinishAdminid(userId);
		}
		boolean update = apply.setState(state).setRemark(reqdata.getRemark()).updateById();

		if (update) {

			if (state == 4) {
				new Maker().setUserid(userid).setState(Constants.user_state_4).setLogouttime(new Date()).updateById();
			}

			//发送微信模板消息
			try {
				wxMessageService.nofityMakerRescissionApply(apply);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return smartResult();
		}
		return optFailSmartResult();
	}
	private boolean checkWhetherPass(MakerRescissionApply apply) {
		//是否还有 项目未付款
		int notCompleteProjectCount = companyProjectMapper.notCompleteProjectCountByUserid(apply.getUserid());
		//是否还有 项目未开票完成（除去已删除的项目）
		int notProjectInvoicedCount = invoiceMapper.notProjectInvoicedCountByUserid(apply.getUserid());
		//是否还有智杰祱项目未开票完成
		int notTaxerProjectInvoicedCount = taxerInvoiceMapper.notTaxerProjectInvoicedCountByUserid(apply.getUserid());
		//是否还有众包项目未付款
		int notCompleteCrowdSourceProjectCount = crowdsourceProjectMapper.notCompleteCrowdSourceProjectCountByUserid(apply.getUserid());
		//是否还有众包项目未开票
		int notCrowdSourceProjectInvoicedCount = crowdsourceInvoiceMapper.notCrowdSourceProjectInvoicedCountByUserid(apply.getUserid());

		if (0 < notCompleteProjectCount || 0 < notProjectInvoicedCount || 0 < notTaxerProjectInvoicedCount ||
				0 < notCompleteCrowdSourceProjectCount || 0 < notCrowdSourceProjectInvoicedCount) {
			return true;
		} else {
			return false;
		}
	}

	public SmartResult openTaxer(BaseSimpleFormBean<OpenTaxerFormBean> formBean) {
		OpenTaxerFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		int userid = reqdata.getUserid();
		int taxer = reqdata.getTaxer();
		// Double serviceRate = reqdata.getTaxerGenLowServiceRate();
		// Date expireDate = reqdata.getExpireDate();
		// int taxerPaid = reqdata.getTaxerPaid();

		MakerStudio studio = new MakerStudio().selectById(userid);
		Maker maker = new Maker().selectById(userid);
		if (studio == null || maker == null) return smartResult(StatusMsg.StatusMsg_201);

		if (taxer == 1) {
			if (MakerType.CROWDSOURCE == maker.getMakerType()) {
				//众包创客目前不能开通纯代理模式
				return smartResult(StatusMsg.StatusMsg_230);
			}
			//开通直接税功能，设置开通时间
			maker.setIssueDate(new Date()).setExpireDate(DateUtil.localDate2Date(LocalDate.now().plusYears(100)));
			studio.setTaxer(1).setTaxertime(new Date());
		} else {
			maker.setIssueDate(null).setExpireDate(null);
			studio.setTaxer(0).setTaxertime(null);
		}

		maker.updateAllColumnById();
		boolean update = studio.updateAllColumnById();
		if (update) return smartResult();
		return optFailSmartResult();
	}

	public SmartResult annualCheck(BaseSimpleFormBean<AnnualCheckFromBean> formBean) {
		AnnualCheckFromBean reqdata = formBean.getReqdata();
		int managerid = formBean.getUserid();
		String year = reqdata.getYear();
		String userids = reqdata.getUserids();

		List<String> useridList;
		if (StringUtil.isEmpty(userids)) {
			useridList = makerStudioMapper.getAllOpenTaxAcctIds();
		} else {
			useridList = Lists.newArrayList(userids.split(","));
		}
		for (String id : useridList){
			List<MakerAnnualCheck> makerAnnualCheck = new MakerAnnualCheck()
					.selectList(Condition.create().eq("userid", id).eq("year",year));
			if (makerAnnualCheck.size() <= 0) {
				String years = makerStudioMapper.getYears(id);
				if (years != null) {
					if (StringUtil.toInt(year) >= StringUtil.toInt(years)) {
						new MakerAnnualCheck()
								.setUserid(StringUtil.toInt(id))
								.setYear(year)
								.setManagerid(managerid)
								.insert();
					}
				}
			}
		}
		return smartResult();

	}

	public SmartResult finalSettlement(BaseSimpleFormBean<FinalSettlementFromBean> formBean) {
		FinalSettlementFromBean reqdata = formBean.getReqdata();
		int managerid = formBean.getUserid();
		String year = reqdata.getYear();
		String userids = reqdata.getUserids();

		List<String> useridList;
		if (StringUtil.isEmpty(userids)) {
			useridList = makerStudioMapper.getAllOpenTaxAcctIds();
		} else {
			useridList = Lists.newArrayList(userids.split(","));
		}
		for (String id : useridList){
			List<MakerFinalSettlement> makerFinalSettlement = new MakerFinalSettlement()
					.selectList(Condition.create().eq("userid", id).eq("year",year));
			if (makerFinalSettlement.size() <= 0) {
				String years = makerStudioMapper.getYears(id);
				if (years != null) {
					if (StringUtil.toInt(year) >= StringUtil.toInt(years)) {
						new MakerFinalSettlement()
								.setUserid(StringUtil.toInt(id))
								.setYear(year)
								.setManagerid(managerid)
								.insert();
					}
				}
			}
		}
		return smartResult();
	}

	public SmartResult getBusinessAuthenticationList(BaseSimpleFormBean<MakerListFormBean> formBean) {
		MakerListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		Integer makerType = reqdata.getMakerType();
		if (makerType == null || makerType == 0) makerType = MakerType.INTELL;

		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		String name = reqdata.getName();
		String inviter = reqdata.getInviter();
		Integer temporaryLogin = reqdata.getTemporaryLogin();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		Integer openingLocation = reqdata.getOpeningLocation();

		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<VerifyingMakerDto> list = makerAccountMapper.getBusinessAuthenticationList(makerType, name, inviter, startDate, endDate,
				openingLocation, temporaryLogin);
		//返回状态备注
		list.stream().forEach(dto -> {
			MakerStatusReason makerStatusReason = new MakerStatusReason().selectOne(Condition.create().eq("userid", dto.getUserid()));
			if (makerStatusReason != null)
				dto.setReason(makerStatusReason.getRealNameReason());
		});
		return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
	}

	public SmartResult saveBusinessAuthenticationImg(BaseSimpleFormBean<BusinessAuthenticationFormBean> formBean) {
		@Valid BusinessAuthenticationFormBean reqdata = formBean.getReqdata();
		int userid = reqdata.getUserid();
		MakerAccount maker = new MakerAccount().selectOne(Condition.create().eq("userid", userid));
		if (maker == null) return SmartResult.fail(StatusMsg.StatusMsg_201);

		String img = reqdata.getImg();
		if (StringUtil.isEmpty(img)) {
			maker.setBusinessAuthenticationState(0);
		} else {
			maker.setBusinessAuthenticationState(1).setOpenStarttime(new Date());
		}
		maker.setBusinessAuthenticationImg(img).updateAllColumnById();
		return SmartResult.success();
	}

	public SmartResult rejectBusinessAuthenticationImg(BaseSimpleFormBean<RejectBusinessAuthenticationFormBean> formBean) {
		@Valid RejectBusinessAuthenticationFormBean reqdata = formBean.getReqdata();
		int userid = reqdata.getUserid();
		String reason = reqdata.getReason();

		MakerAccount account = new MakerAccount().selectOne(Condition.create().eq("userid", userid));
		if (account == null) return SmartResult.fail(StatusMsg.StatusMsg_201);

		account.setBusinessAuthenticationState(2).setBusinessAuthenticationReason(reason).updateById();

		Maker maker = new Maker().selectById(userid);
		wxMessageService.notifyBusinessAuthenticationFailed(account.getRealname(), maker.getOpenid(), reason, maker.getUserid());
		return smartResult();
	}

	public SmartResult editCoreModule(BaseSimpleFormBean<CoreModuleFormBean> formBean) {
		@Valid CoreModuleFormBean reqdata = formBean.getReqdata();
		int userid = reqdata.getUserid();
		String coreModule = reqdata.getCoreModule();

		MakerAccount account = new MakerAccount().selectOne(Condition.create().eq("userid", userid));
		if (account == null) return smartResult(StatusMsg.StatusMsg_201);

		account.setCoreModule(coreModule).updateAllColumnById();
		return smartResult();
	}

	public SmartResult editStudioBrokerageComputeState(BaseSimpleFormBean<StudioBrokerageComputeFormBean> formBean) {

		@Valid StudioBrokerageComputeFormBean reqdata = formBean.getReqdata();
		new MakerStudio().setUserid(reqdata.getUserid()).setBrokerageComputeState(reqdata.getState()).updateById();
		return smartResult();
	}

	/**
	 * 查看政府审核状态
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult governmentExamineState(BaseSimpleFormBean<Integer> formBean) {
		if (null == formBean) {
			return smartResult(StatusMsg.StatusMsg_101);
		}
		int userid = formBean.getReqdata();
		MakerAccount account = new MakerAccount().selectOne(Condition.create().eq("userid", userid));
		if (account == null) return smartResult(StatusMsg.StatusMsg_201);
		if (StringUtil.isEmpty(account.getIndividualAccountNumber())) {
			return smartResult(StatusMsg.StatusMsg_224);
		}
		String firmid = account.getIndividualAccountNumber();

		RestTemplate restTemplate = new RestTemplate();
		GovernmentExamineStateFormBean governmentExamineStateFormBean = new GovernmentExamineStateFormBean();
		governmentExamineStateFormBean.setFIRMID(firmid);
		BaseSimpleFormBean<GovernmentExamineStateFormBean> formBean1 = new BaseSimpleFormBean<>();
		formBean1.setReqdata(governmentExamineStateFormBean);
		GovermentExamineStateMakerDto govermentExamineStateMakerDto = new GovermentExamineStateMakerDto();
		//调用政府审核状态
		SmartResult result = restTemplate.postForObject(zddUrlConfig.getYunkongUrl() + yunKongConfig.getGovernmentExamineState(),
				formBean1,
				SmartResult.class);
		if (result != null && result.getState() == StatusMsg.StatusMsg_100.getState()) {
			JSONObject object = result.toJson().getJSONObject("object");
			if (StringUtil.isEmpty(object.getString("STATE"))) {
				LogUtil.error("调用政府审核状态失败，未返回审核状态！返回信息：" + object.toJSONString());
				return smartResult(StatusMsg.StatusMsg_199);
			} else {
				//直接记录返回值 审核状态 驳回原因 营业执照编号
				account.setGovernmentExamineState(object.getString("STATE"))
						.setGovernmentRejectionReasons(object.getString("FJREASON"))
						.setBusinessLicenseNo(object.getString("YYZZNO"));
				if (!account.updateById()) {
					LogUtil.error("保存政府审核状态失败");
					return smartResult(StatusMsg.StatusMsg_199);
				}
				govermentExamineStateMakerDto.setGovernmentExamineState(object.getString("STATE"))
						.setGovernmentRejectionReasons(object.getString("FJREASON"))
						.setBusinessLicenseNo(object.getString("YYZZNO"));
				//审核通过
				if ("1".equals(object.getString("STATE"))) {
					//审核通过会返回营业执照图片的base64格式
					String oss_object = DateUtil.getNowDateString(DateUtil.FORMAT_STYLE_8);
					String fileName = UUID.randomUUID().toString() + ".png";
					String imgFilePath = uploadPathConfig.getUploadpath() + "/" + oss_object + "/" + fileName;
					File file = ImgBase64Util.Base64ToImg(object.getString("YYZZPATHBase"), imgFilePath);
					if (null == file) {
						LogUtil.error("调用政府审核状态，base64转图片失败! 个体户编号：" + firmid);
						return smartResult(StatusMsg.StatusMsg_199);
					}
					//保存营业执照的路径
					account.setBusiness_license_pic(oss_object + "/" + fileName);
					//营业执照路径放到dto中返回到前端
					govermentExamineStateMakerDto.setBusinessLicensePic(oss_object + "/" + fileName);
					if (account.updateById()) {
						//获取创客银行卡信息
						MakerBankcard makerBankcard = new MakerBankcard().selectOne(Condition.create().eq("userid", userid));
						if (null == makerBankcard) {
							return smartResult(StatusMsg.StatusMsg_226);
						}
						if (StringUtil.isEmpty(makerBankcard.getAcctno())) {
							makerBankcard.setPuchBankCardErrorMsg("创客政府审核通过后向共青城推送银行卡信息失败，未获取到银行卡号。").updateById();
							return smartResult(govermentExamineStateMakerDto);
						}
						//向共青城推送银行卡信息
						SmartResult resultBank = crowdsourceService.saveBank(firmid, makerBankcard.getAcctno());
						if (resultBank != null && resultBank.getState() == StatusMsg.StatusMsg_100.getState()) {
							String yunKongId = resultBank.getObject().toString();
							makerBankcard.setYunkongId(yunKongId).setYunkongAcctno(makerBankcard.getAcctno()).updateById();
							return smartResult(govermentExamineStateMakerDto);
						} else {
							if (null != resultBank && StringUtil.isNotEmpty(resultBank.getMsg())) {
								//保存向共青城推送银行卡的错误信息提示
								makerBankcard.setPuchBankCardErrorMsg(resultBank.getMsg()).updateById();
							} else {
								makerBankcard.setPuchBankCardErrorMsg("创客政府审核通过后向共青城推送银行卡信息失败，返回信息为空").updateById();
							}
							return smartResult(govermentExamineStateMakerDto);
						}
					} else {
						LogUtil.error("调用政府审核状态，保存营业执照存储路径失败！个体户编号：" + firmid + "，营业执照存储路径为：" + oss_object + "/" + fileName);
						return smartResult(StatusMsg.StatusMsg_199);
					}
				} else {
					//政府驳回注册通知  注释掉 驳回后共青城会 通知的
					//					wxMessageService.examineMakerToBusinessInfoNotify(account.getAcctid(),2);
					return smartResult(govermentExamineStateMakerDto);
				}
			}
		} else {
			if (null != result && StringUtil.isNotEmpty(result.getMsg())) {
				com.info.zhiduoduo.common.utils.LogUtil.error("调用政府审核状态失败！返回值为:" + result.toString());
				return SmartResult.fail(result.getMsg());
			} else {
				com.info.zhiduoduo.common.utils.LogUtil.error("调用政府审核状态失败！返回信息为空");
				return smartResult(StatusMsg.StatusMsg_199);
			}
		}
	}

	/**
	 * 查看政府审核状态定时任务
	 */
	public void checkGovernmnetAuditState() {
		LogUtil.info("进入 查看政府审核创客状态定时任务！！！");
		//需要查看政府审核状态的创客
		List<MakerAccount> list = makerAccountMapper.getNeedGovernmentAudit();
		BaseSimpleFormBean<Integer> formBean = new BaseSimpleFormBean<>();
		list.forEach(maker -> {
			formBean.setReqdata(maker.getUserid());
			governmentExamineState(formBean);
		});

	}

	/**
	 * 编辑 未审核该创客原因
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult editZddNoSuditReason(@RequestBody BaseSimpleFormBean<EditZddNoAuditReasonFormBean> formBean) {
		if (null == formBean || 0 == formBean.getReqdata().getUserid() || StringUtil.isEmpty(formBean.getReqdata().getZddNoAuditReason())) {
			return errorParamSmartResult();
		}
		EditZddNoAuditReasonFormBean data = formBean.getReqdata();
		MakerAccount makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", data.getUserid()));
		if (null == makerAccount) {
			return smartResult(StatusMsg.StatusMsg_201);
		}
		makerAccount.setZddNoAuditReason(data.getZddNoAuditReason());
		if (!makerAccount.updateById()) {
			return smartResult(StatusMsg.StatusMsg_199);
		}
		return smartResult();
	}

	/**
	 * 修改创客开户地
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult updateOpeningLocation(BaseSimpleFormBean<UpdateOpeningLocationFormBean> formBean) {
		if (null == formBean || null == formBean.getReqdata() || null == formBean.getReqdata().getUseridList() ||
				0 == formBean.getReqdata().getOpeningLocation()) {
			return errorParamSmartResult();
		}
		List<Integer> useridList = formBean.getReqdata().getUseridList();
		for (Integer userid : useridList) {
			//获取创客实名信息
			MakerAccount account = new MakerAccount().selectOne(Condition.create().eq("userid", userid));
			if (null == account) {
				return smartResult(StatusMsg.StatusMsg_201);
			}
			account.setOpeningLocation(formBean.getReqdata().getOpeningLocation());
			if (!account.updateById()) {
				return smartResult(StatusMsg.StatusMsg_199);
			}
		}
		return smartResult();
	}

	/**
	 * 审核创客的签名，视频等信息，通过就注册个体户
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult examineMakerToBusinessInfo(@RequestBody BaseSimpleFormBean<AuditMakerInfoFormBean> formBean) {
		if (null == formBean || 0 == formBean.getReqdata().getUserid() || 0 == formBean.getReqdata().getExamineBusinessDataState()) {
			return errorParamSmartResult();
		}
		AuditMakerInfoFormBean reqdata = formBean.getReqdata();
		MakerAccount makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", reqdata.getUserid()));
		if (makerAccount == null) {
			return SmartResult.fail(StatusMsg.StatusMsg_201);
		}
		if (1 == reqdata.getExamineBusinessDataState()) {
			//审核通过 直接去共青城注册个体户
			//有两种认证通道
			// 第一通道顺序：身份认证-实名认证-活体检测  第二认证通道顺序：身份认证-活体检测-实名认证
			//若要更换认证通道 只需在 配置文件中 解开对应的接口路径注释 ，然后再更换 下面一二三 这三段代码的顺序 注意：云控包下的 身份认证代码中有段需要改的 上面也已写注释 一看就懂
			//现在使用第一通道  顺序为 身份认证-实名认证-活体检测

			//一  推送正反面身份证
			LogUtil.info("推送正面身份证!");
			String positive = "";
			SmartResult resultPositive = makerIdentityConfirm(makerAccount.getUserid(), "0");
			if (resultPositive != null && resultPositive.getState() == StatusMsg.StatusMsg_100.getState()) {
				JSONObject object = resultPositive.toJson().getJSONObject("object");
				//身份证正面流水号
				positive = object.getString("PLATSRL");
				LogUtil.info("身份证正面流水号：" + positive);
			} else {
				return resultPositive;
			}
			LogUtil.info("推送反面身份证!");
			String otherSide = "";
			SmartResult resultOtherSide = makerIdentityConfirm(makerAccount.getUserid(), "1");
			if (resultOtherSide != null && resultOtherSide.getState() == StatusMsg.StatusMsg_100.getState()) {
				JSONObject object = resultOtherSide.toJson().getJSONObject("object");
				//身份证反面流水号
				otherSide = object.getString("PLATSRL");
				LogUtil.info("身份证反面流水号：" + otherSide);
			} else {
				return resultOtherSide;
			}

			//二  实名认证
			LogUtil.info("实名认证!");
			String realName = "";
			//注意！ 第二个参数传递：使用通道一：身份证正面流水号    使用通道二：活体视频流水号
			SmartResult resultReal = realNameConfirm(makerAccount, positive);
			if (resultReal != null && resultReal.getState() == StatusMsg.StatusMsg_100.getState()) {
				JSONObject object = resultReal.toJson().getJSONObject("object");
				//实名认证流水号
				realName = object.getString("PLATSTR");
				LogUtil.info("实名认证返回参数：" + object.toString());
				LogUtil.info("实名认证流水号：" + realName);
			} else {
				return resultReal;
			}

			//三 活体检测
			LogUtil.info("推送视频做活体检测!");
			String face = "";
			SmartResult resultFace = makerDetectionByUserId(makerAccount.getUserid(), positive);
			if (resultFace != null && resultFace.getState() == StatusMsg.StatusMsg_100.getState()) {
				JSONObject object = resultFace.toJson().getJSONObject("object");
				//活体检测流水号
				face = object.getString("PLATSTR");
				LogUtil.info("活体检测流水号：" + face);
			} else {
				return resultFace;
			}

			LogUtil.info("注册个体户!");
			//四 注册个体户
			return registeredBusiness(makerAccount, positive, otherSide, realName, face);
		} else {
			//审核驳回
			makerAccount.setRejectBusinessRegisterReason(reqdata.getReasons())
					.setExamineBusinessDataState(reqdata.getExamineBusinessDataState());
			if (!makerAccount.updateById()) {
				return smartResult(StatusMsg.StatusMsg_199);
			} else {
				//审核失败发送消息给用户 重新提交资料
				Maker maker = new Maker().selectById(makerAccount.getUserid());
				if (maker.getMakerType() == MakerType.CROWDSOURCE) {
					wxCrowdsourceMessageService.examineMakerToBusinessInfoNotify(makerAccount.getAcctid(), 1);
				} else {
					wxMessageService.examineMakerToBusinessInfoNotify(makerAccount.getAcctid(), 1);
				}
				return smartResult();
			}
		}
	}

	/**
	 * 创客调用身份验证 直接从创客信息中拿身份证
	 *
	 * @param userid 创客userid
	 * @param side   0 正面  1 反面
	 * @return 流水号
	 */
	private SmartResult makerIdentityConfirm(int userid, String side) {
		RestTemplate restTemplate = new RestTemplate();
		MakerIdentityConfirmBean makerIdentityConfirmBean = new MakerIdentityConfirmBean();
		makerIdentityConfirmBean.setSide(side).setUserId(userid);
		BaseSimpleFormBean<MakerIdentityConfirmBean> formBean = new BaseSimpleFormBean<>();
		formBean.setReqdata(makerIdentityConfirmBean);

		return restTemplate.postForObject(zddUrlConfig.getYunkongUrl() + yunKongConfig.getMakerIdentityConfirm(), formBean,
				SmartResult.class);
	}

	/**
	 * 创客调用实名认证
	 *
	 * @param makerAccount makerAccount
	 * @param positive     使用通道一：身份证正面流水号    使用通道二：活体视频流水号
	 * @return success
	 */
	private SmartResult realNameConfirm(MakerAccount makerAccount, String positive) {
		RestTemplate restTemplate = new RestTemplate();
		RealNameConfirmFormBean realNameConfirmFormBean = new RealNameConfirmFormBean();
		realNameConfirmFormBean.setNAME(makerAccount.getRealname()).setCERT_ID(makerAccount.getIdno()).setSFZMOCRPLATSRL(positive);
		BaseSimpleFormBean<RealNameConfirmFormBean> formBean = new BaseSimpleFormBean<>();
		formBean.setReqdata(realNameConfirmFormBean);
		return restTemplate.postForObject(zddUrlConfig.getYunkongUrl() + yunKongConfig.getRealNameConfirm(), formBean, SmartResult.class);
	}

	/**
	 * 创客调用活体检测ByUserid
	 *
	 * @param userid   创客id
	 * @param positive 身份证正面流水号
	 * @return success
	 */
	private SmartResult makerDetectionByUserId(int userid, String positive) {
		RestTemplate restTemplate = new RestTemplate();
		MakerDetectionByUserIdformBean makerDetectionByUserIdformBean = new MakerDetectionByUserIdformBean();
		makerDetectionByUserIdformBean.setUserId(userid).setSFZMOCRPLATSRL(positive);

		BaseSimpleFormBean<MakerDetectionByUserIdformBean> formBean = new BaseSimpleFormBean<>();
		formBean.setReqdata(makerDetectionByUserIdformBean);
		return restTemplate.postForObject(zddUrlConfig.getYunkongUrl() + yunKongConfig.getMakerDetectionByUserId(), formBean,
				SmartResult.class);
	}

	/**
	 * 注册工商户
	 *
	 * @param makerAccount 创客信息
	 * @param positive     身份证正面流水号
	 * @param otherSide    身份证反面流水号
	 * @param realName     实名认证流水
	 * @param face         活体检测流水
	 * @return success
	 */
	private SmartResult registeredBusiness(MakerAccount makerAccount, String positive, String otherSide, String realName, String face) {
		try {
			File f;
			com.info.zhiduoduo.common.utils.LogUtil.info(
					"要压缩的创客签名参数：" + uploadPathConfig.getOssimgurl() + makerAccount.getElectronicSignature() +
							"?x-oss-process=image/resize,h_22,m_lfit/format,jpg");
			String compressPath = FileUtil.downloadFile(uploadPathConfig.getOssimgurl() + makerAccount.getElectronicSignature() +
					"?x-oss-process=image/resize,h_22,m_lfit/format,jpg", uploadPathConfig.getUploadpath(), 2, "compress");
			com.info.zhiduoduo.common.utils.LogUtil.info("压缩后的创客签名的路径：" + compressPath);
			if (null == compressPath) {
				f = new File(uploadPathConfig.getUploadpath() + "/" + makerAccount.getElectronicSignature());
			} else {
				f = new File(uploadPathConfig.getUploadpath() + "/" + compressPath);
			}
			Maker maker = new Maker().selectById(makerAccount.getUserid());
			//电子签名转为base64
			String signInfo = FileUtil.fileToBase64(f);
			YunKongRegisteredBusinessFormBean bean = new YunKongRegisteredBusinessFormBean();
			bean.setSIGN(signInfo)
					.setHUITIPLATSRL(face)
					.setSFGHOCRPLATSRL(otherSide)
					.setSFZMOCRPLATSRL(positive)
					.setMOBILENO(maker.getPhone())
					.setSFRZDBLATSRL(realName);
			RestTemplate restTemplate = new RestTemplate();
			BaseSimpleFormBean<YunKongRegisteredBusinessFormBean> registeredBusinessFormBean = new BaseSimpleFormBean<>();
			registeredBusinessFormBean.setReqdata(bean);
			SmartResult result = restTemplate.postForObject(zddUrlConfig.getYunkongUrl() + yunKongConfig.getBusiness(),
					registeredBusinessFormBean, SmartResult.class);
			if (result != null && result.getState() == StatusMsg.StatusMsg_100.getState()) {
				JSONObject object = result.toJson().getJSONObject("object");
				//获取返回回来的个体户编号
				String firmid = object.getString("FIRMID");
				makerAccount.setIndividualAccountNumber(firmid);
				if (!makerAccount.updateById()) {
					com.info.zhiduoduo.common.utils.LogUtil.error("注册工商户！保存个体户编号失败！");
					return smartResult(StatusMsg.StatusMsg_199);
				} else {
					//默认审核通过创客个体户
					CompanyExamineFormBean companyExamineFormBean = new CompanyExamineFormBean();
					companyExamineFormBean.setFIRMID(firmid).setSTATUS("1");
					BaseSimpleFormBean<CompanyExamineFormBean> companyExamineBean = new BaseSimpleFormBean<>();
					companyExamineBean.setReqdata(companyExamineFormBean);
					SmartResult result2 = restTemplate.postForObject(zddUrlConfig.getYunkongUrl() + yunKongConfig.getCompanyExamineMaker(),
							companyExamineBean, SmartResult.class);
					if (result2 != null && result2.getState() == StatusMsg.StatusMsg_100.getState()) {
						JSONObject object1 = result2.toJson().getJSONObject("object");
						if (!"true".equals(object1.getString("msg"))) {
							com.info.zhiduoduo.common.utils.LogUtil.error("创客企业审核审核失败！个体户编号：" + firmid);
							return smartResult(StatusMsg.StatusMsg_199);
						} else {
							makerAccount.setGongQingDataSubmint(1)
									.setGovernmentExamineState("")
									.setGovernmentRejectionReasons("")
									.setExamineBusinessDataState(1)
									.updateById();
							return smartResult();
						}
					} else {
						com.info.zhiduoduo.common.utils.LogUtil.error("创客企业审核审核失败！个体户编号：" + firmid);
						return smartResult(StatusMsg.StatusMsg_199);
					}
				}
			} else {
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return smartResult(StatusMsg.StatusMsg_199);
		}
	}

	/**
	 * 编辑创客注册个体户需要的签名，视频等信息
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult editMakerToBusinessInfo(BaseSimpleFormBean<EditMakerToBusinessFormBean> formBean) {
		if (null == formBean || 0 == formBean.getReqdata().getUserid()) {
			return errorParamSmartResult();
		}
		EditMakerToBusinessFormBean editMakerToBusinessFormBean = formBean.getReqdata();
		MakerAccount makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", editMakerToBusinessFormBean.getUserid()));
		if (makerAccount == null) {
			return SmartResult.fail(StatusMsg.StatusMsg_201);
		}

		BeanUtils.copyProperties(editMakerToBusinessFormBean, makerAccount);
		if (!makerAccount.updateById()) {
			return smartResult(StatusMsg.StatusMsg_199);
		} else {
			return smartResult();
		}
	}

	/**
	 * 查看创客注册个体户的签名，视频等信息
	 *
	 * @param formBean vv
	 * @return GetMakerToBusinessInfoDto
	 */
	public SmartResult<GetMakerToBusinessInfoDto> getMakerToBusinessInfo(BaseSimpleFormBean<Integer> formBean) {
		if (null == formBean || null == formBean.getReqdata()) {
			return errorParamSmartResult();
		}
		int userId = formBean.getReqdata();
		MakerAccount makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", userId));
		if (makerAccount == null) {
			return SmartResult.fail(StatusMsg.StatusMsg_201);
		}
		GetMakerToBusinessInfoDto getMakerToBusinessInfoDto = new GetMakerToBusinessInfoDto();
		BeanUtils.copyProperties(makerAccount, getMakerToBusinessInfoDto);
		return smartResult(getMakerToBusinessInfoDto);
	}

	/**
	 * 共青城创客，已实名未上传视频的，每天推送一次微信通知，最多提醒5次
	 */
	public void reminderToSubmitData() {
		List<Maker> makerList = makerAccountMapper.reminderToSubmitData();
		if (null != makerList) {
			makerList.forEach(maker -> {
				if (maker.getMakerType() == MakerType.INTELL) {
					MakerAccount makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", maker.getUserid()));
					wxMessageService.reminderToSubmitData(maker.getOpenid(), makerAccount.getRealname(), maker.getUserid());
				} else if (maker.getMakerType() == MakerType.CROWDSOURCE) {
					MakerAccount makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", maker.getUserid()));
					wxCrowdsourceMessageService.reminderToSubmitData(maker.getOpenid(), makerAccount.getRealname(),
							makerAccount.getUserid());
				}
				MakerAccount makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", maker.getUserid()));
				//提醒次数加一
				makerAccount.setNumberOfRemindToSubmitData(makerAccount.getNumberOfRemindToSubmitData() + 1).updateById();
			});
		}
	}

	/**
	 * 暂不处理的创客列表
	 *
	 * @param formBean formBean
	 * @return VerifyingMakerDto
	 */
	public SmartResult getTemporarilyNotHandledList(BaseSimpleFormBean<TemporarilyNotHandledFormBean> formBean) {
		TemporarilyNotHandledFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		Integer makerType = reqdata.getMakerType();
		if (makerType == null || makerType == 0) makerType = MakerType.INTELL;
		//获取地址
		SystemManager systemManager =new SystemManager().selectOne(Condition.create().eq("managerid", formBean.getUserid()));
		if (systemManager==null) return optFailSmartResult();
		String dockingCity = systemManager.getDockingCity();

		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		String name = reqdata.getName();
		String companme = reqdata.getBindcompname();

		if (startDate == null) {
			startDate = new Date(0);
		}
		if (endDate == null) {
			endDate = new Date();
		}

		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<TemporarilyNotHandledDto> list = makerAccountMapper.getTemporarilyNotHandledList(makerType, name, startDate, endDate,
				companme,dockingCity);
		return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
	}

	/**
	 * 编辑创客目前是否处理
	 *
	 * @param formBean formBean
	 * @return success
	 */
	public SmartResult setMarkWhetherHandled(BaseSimpleFormBean<SetMakerWhetherHandledFormBean> formBean) {
		if (null == formBean || null == formBean.getReqdata() || 0 == formBean.getReqdata().getUserid()) {
			return errorParamSmartResult();
		}
		SetMakerWhetherHandledFormBean reqdata = formBean.getReqdata();
		MakerAccount makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", reqdata.getUserid()));
		if (null == makerAccount) {
			return smartResult(StatusMsg.StatusMsg_201);
		}
		if (1 == reqdata.getTemporarilyNotHandled()) {
			// 暂不处理
			makerAccount.setTemporarilyNotHandled(reqdata.getTemporarilyNotHandled())
					.setNotHandledReason(reqdata.getNotHandledReason())
					.setNotHandledVoucher(reqdata.getNotHandledVoucher());
		} else if (0 == reqdata.getTemporarilyNotHandled()) {
			//恢复为 处理
			makerAccount.setTemporarilyNotHandled(reqdata.getTemporarilyNotHandled());
		} else {
			return errorParamSmartResult();
		}
		if (makerAccount.updateById()) {
			return smartResult();
		} else {
			return smartResult(StatusMsg.StatusMsg_199);
		}
	}

	/**
	 * 改变工作室注册地-会新增创客数据
	 *
	 * @param formBean
	 * @return
	 */
	@Transactional
	public synchronized SmartResult changeStudioOpenAdress(BaseSimpleFormBean<ChangeStudioOpenAdressFormBean> formBean) {
		if (null == formBean || null == formBean.getReqdata() || 0 == formBean.getReqdata().getUserid() ||
				2 == formBean.getReqdata().getNewOpeningLocation()) {
			return errorParamSmartResult();
		}
		ChangeStudioOpenAdressFormBean reqdata = formBean.getReqdata();
		int userid = reqdata.getUserid();
		String newStudioName = reqdata.getNewStudioName();
		int newOpeningLocation = reqdata.getNewOpeningLocation();
		//原创客信息
		Maker maker = new Maker().selectById(userid);
		MakerAccount makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", userid));

		MakerStudio makerStudio = new MakerStudio().selectById(userid);
		makerStudio.setStudionickname(null);
		if (null == maker || null == makerAccount) {
			return smartResult(StatusMsg.StatusMsg_201);
		}
		MakerBankcard makerBankcard = new MakerBankcard().selectOne(
				Condition.create().eq("state", 1).eq("userid", userid).eq("accttype", 1));
		if (null == makerBankcard) {
			return smartResult(StatusMsg.StatusMsg_226);
		}
		if (null == makerStudio) {
			return smartResult(StatusMsg.StatusMsg_228);
		}
		//新增 Maker
		Maker newMaker = new Maker();
		BeanUtils.copyProperties(maker, newMaker);
		// 判断是 创客，有效期expireDate，在表zdd_maker里面，复制的时候按当前年+1，比如今天是2021/1/29，那有效期就到2022/1/29
		if (makerStudio.getTaxer() == 1) {
			newMaker.setIssueDate(DateUtil.nowDate()).setExpireDate(DateUtil.addYear(DateUtil.nowDate(), 1));
		}
		//新的工作室用户状态默认2
		newMaker.setState(Constants.user_state_2);
		//更新时间
		newMaker.setCreatetime(new Date());
		if (!newMaker.setUserid(null).insert()) {
			throw SmartException.of(StatusMsg.StatusMsg_199);
		}
		//原创客手机号后拼上 off  删除原创客的openid(也就是设为空)
		maker.setPhone(maker.getPhone() + "off").setOpenid("").setTaxerOpenid("");
		if (!maker.updateById()) {
			throw SmartException.of(StatusMsg.StatusMsg_199);
		}

		//新增 MakerAccount
		MakerAccount newMakerAccount = new MakerAccount();
		BeanUtils.copyProperties(makerAccount, newMakerAccount);
		//设置更新时间
		newMakerAccount.setAcctid(null)
				.setUserid(newMaker.getUserid())
				.setOpeningLocation(newOpeningLocation)
				.setCreatetime(new Date())
				.setUpdatetime(new Date());
		if (newMakerAccount.getOpenStarttime() != null) {
			newMakerAccount.setOpenStarttime(new Date());
		}
		if (newMakerAccount.getAuthSubmitTime() != null) {
			newMakerAccount.setAuthSubmitTime(new Date());
		}
		if (newMakerAccount.getAuthPassTime() != null) {
			newMakerAccount.setAuthPassTime(new Date());
		}
		if (!newMakerAccount.insert()) {
			throw SmartException.of(StatusMsg.StatusMsg_199);
		}
		//原创客 的 身份证号后拼off
		makerAccount.setIdno(makerAccount.getIdno() + "off");
		if (!makerAccount.updateById()) {
			throw SmartException.of(StatusMsg.StatusMsg_199);
		}
		if (makerBankcard != null) {
			//新增 zdd_maker_bankcard
			MakerBankcard newMakerBankcard = new MakerBankcard();
			BeanUtils.copyProperties(makerBankcard, newMakerBankcard);
			//设置更新时间
			newMakerBankcard.setId(null).setUserid(newMaker.getUserid()).setCreatetime(new Date());
			if (!newMakerBankcard.insert()) {
				throw SmartException.of(StatusMsg.StatusMsg_199);
			}
		}

		//新增 zdd_maker_studio
		MakerStudio newMakerStudio = new MakerStudio();
		BeanUtils.copyProperties(makerStudio, newMakerStudio);
		//设置更新时间
		newMakerStudio.setUserid(newMaker.getUserid()).setUsername(newStudioName).setCreatetime(new Date()).setUpdatetime(new Date());
		if (newMakerStudio.getOpenTaxAcctStarttime() != null) {
			newMakerStudio.setOpenTaxAcctStarttime(new Date());
		}
		if (newMakerStudio.getOpenTaxAcctFinishtime() != null) {
			newMakerStudio.setOpenTaxAcctFinishtime(new Date());
		}
		if (newMakerStudio.getTaxertime() != null) {
			newMakerStudio.setTaxertime(new Date());
		}
		if (newMakerStudio.getOpenFinishtime() != null) {
			newMakerStudio.setOpenFinishtime(new Date());
		}
		// 修改工作室状态：放到 【开户工作室】列表
		newMakerStudio.setState(StudioState.CREATING).setOpenTaxAcct(0).setTaxAcctState(1);
		if (!newMakerStudio.insert()) {
			throw SmartException.of(StatusMsg.StatusMsg_199);
		}

		//发送开户通知信息
		MakerDetailDto makerDetailDto = getUserInfo(newMaker.getUserid());
		boolean sendSuccess = sendOpenStudioNotice(makerDetailDto, newMakerStudio.getUsername());
		if (!sendSuccess) {
			return optFailSmartResult();
		}

		return smartResult();
	}

	public SmartResult addCancelVoucher(BaseSimpleFormBean<MakerCancelVoucher> formBean) {
		if (formBean == null || formBean.getReqdata() == null) {
			return errorParamSmartResult();
		}
		MakerCancelVoucher reqdata = formBean.getReqdata();
		Maker maker = new Maker().selectById(reqdata.getUserid());
		if (maker == null) {
			return smartResult(StatusMsg.StatusMsg_102);
		}
		maker.setCancelVoucher(reqdata.getCancelVoucher());
		if (!maker.updateById()) {
			throw SmartException.of(StatusMsg.StatusMsg_199);
		}
		return smartResult();

	}

	public String conditionTemplate(BaseSimpleFormBean formBean) {
		//根据userid查出对应的管理员的dockingCity
		SmartResult<SystemManager> systemManagerById = systemService.getSystemManagerById(formBean);
		SystemManager systemManager = systemManagerById.getObject();
		String dockingCity = null;
		if (systemManager != null) {
			dockingCity = systemManager.getDockingCity();
		}

		if (dockingCity != null && dockingCity.length() != 0) {
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append(" and opening_location in (");
			String[] split = dockingCity.split(",");
			for (String str : split) {
				stringBuilder.append(str).append(",");
			}
			stringBuilder.setCharAt(stringBuilder.length() - 1, ')');
			return stringBuilder.toString();
		} else {
			return "";
		}
	}

	public void fixStandardServiceRate() {
		new Thread(() -> {
			log.info("开始修复费率");
			StringBuilder sb = new StringBuilder();
			sb.append(" and us.gen_low_service_rate=")
					.append(commonConfig.getGenLowServiceRate())
					.append(" and us.gen_high_service_rate=")
					.append(commonConfig.getGenHighServiceRate())
					.append(" and us.gen_high_tax_rate=")
					.append(commonConfig.getGenHighTaxRate())
					.append(" and us.spe_service_rate=")
					.append(commonConfig.getSpeServiceRate())
					.append(" and us.spe_tax_rate=")
					.append(commonConfig.getSpeTaxRate())
					.append(" and us.yearly_high_tax_rate=")
					.append(commonConfig.getYearlyHighTaxRate())
					.append(" and us.yearly_high_service_rate=")
					.append(commonConfig.getYearlyHighServiceRate())
					.append(" and us.yearly_high_2_tax_rate=")
					.append(commonConfig.getYearlyHigh2TaxRate())
					.append(" and us.yearly_high_2_service_rate=")
					.append(commonConfig.getYearlyHigh2ServiceRate())
					.append(" and us.yearly_high_3_tax_rate=")
					.append(commonConfig.getYearlyHigh3TaxRate())
					.append(" and us.yearly_high_3_service_rate=")
					.append(commonConfig.getYearlyHigh3ServiceRate());
			List<MakerStudio> list = makerMapper.getStandardServiceRateList(sb.toString());
			for (MakerStudio studio : list) {
				studio.setGenLowServiceRate(0.03)
						.setGenHighServiceRate(0.03)
						.setGenHighTaxRate(0.01)
						.setSpeServiceRate(0.03)
						.setSpeTaxRate(0.01)
						.setYearlyHighServiceRate(0.03)
						.setYearlyHighTaxRate(0.01)
						.setYearlyHigh2ServiceRate(0.03)
						.setYearlyHigh2TaxRate(0.01)
						.setYearlyHigh3ServiceRate(0.03)
						.setYearlyHigh3TaxRate(0.01)
						.updateById();
			}
			log.info("费率修复完成-------------------------------------------------");
		}).start();
	}

	public SmartResult queryExpertLabel(BaseSimpleFormBean<Integer> formBean) {
		QueryExpertLabelDto queryExpertLabelDtos = makerStudioMapper.queryExpertLabel(formBean.getReqdata());
		return smartResult(queryExpertLabelDtos);
	}

	public SmartResult updateExpertLabel(@RequestBody BaseSimpleFormBean<UpdateExpertLabelFormBean> formBean) {
		if (formBean == null || formBean.getReqdata() == null) {
			return errorParamSmartResult();
		}
		UpdateExpertLabelFormBean reqdata = formBean.getReqdata();
		MakerAccount makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", reqdata.getUserid()));
		if (!ObjectUtils.isEmpty(makerAccount)) {
			boolean b1 = makerAccount.setResidence(reqdata.getResidence())
					.setExpertLabelState(reqdata.getExpertLabelState())
					.setExpertIndustry(reqdata.getExpertIndustry())
					.setExpertSkillExpertise(reqdata.getExpertSkillExpertise())
					.setExpertLabel(reqdata.getExpertLabel())
					.setExpertRemarks(reqdata.getExpertRemarks())
					.setExpertIndustryLabel(reqdata.getExpertIndustryLabel())
					.setExpertRegionLabel(reqdata.getExpertRegionLabel())
					.setExpertIntro(reqdata.getIntro())
					.updateById();
		}
		MakerStudio makerStudio = new MakerStudio().selectById(reqdata.getUserid());
		if (!ObjectUtils.isEmpty(makerStudio)) {
			makerStudio.setIntro(reqdata.getIntro()).updateById();
		}

		return smartResult();
	}

	/**
	 * 查询开启专家标签列表
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult queryExpertLabelTab(BaseSimpleFormBean<QueryExpertLabelTabFormBean> formBean) {
		if (formBean == null || formBean.getReqdata() == null) {
			return errorParamSmartResult();
		}
		QueryExpertLabelTabFormBean reqdata = formBean.getReqdata();
		String condition = reqdata.getCondition();
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<QueryExpertLabelDto> queryExpertLabelDtos = makerStudioMapper.queryExpertLabelTab(condition);
		return smartResult(queryExpertLabelDtos, page.getTotal(), page.getPages(), page.getPageNum());
	}

	/**
	 * 按照创客名称和工作室名称查询工作室
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult queryMakerName(BaseSimpleFormBean<String> formBean) {
		if (formBean == null || formBean.getReqdata() == null) {
			return errorParamSmartResult();
		}
		String reqdata = formBean.getReqdata();
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<QueryMakerNameDto> queryMakerNameDtos = makerMapper.queryMakerDto(reqdata);
		return smartResult(queryMakerNameDtos, page.getTotal(), page.getPages(), page.getPageNum());
	}

	public SmartResult updateMakerLonginType(BaseSimpleFormBean<UpdateMakerLonginTypeFormBean> formBean) {
		if (formBean == null || formBean.getReqdata() == null) {
			return errorParamSmartResult();
		}
		UpdateMakerLonginTypeFormBean reqdata = formBean.getReqdata();
		MakerAccount makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", reqdata.getUserid()));
		Asserts.notNull(makerAccount);
		Asserts.isTrue(makerAccount.setTemporaryLogin(reqdata.getTemporaryLogin()).updateById());
		return smartResult();
	}

	public SmartResult saveEntrustTaxVideo(BaseSimpleFormBean<SaveEntrustTaxVideoFormBean> formBean) {
		SaveEntrustTaxVideoFormBean reqdata = formBean.getReqdata();
		Asserts.notEmpty(reqdata.getFilePath(), StatusMsg.StatusMsg_101);
		int userid = reqdata.getUserid();
		MakerDetailDto userDetail = makerMapper.getUserDetail(userid);
		MakerStudio makerStudio = new MakerStudio().selectById(userid);
		Asserts.notNull(makerStudio, StatusMsg.StatusMsg_228);
		// 支持芜湖地区创客
		Asserts.equals(userDetail.getOpeningLocation(), 3, StatusMsg.StatusMsg_259);

		makerStudio.setEntrustTaxVideoFile(reqdata.getFilePath()).setEntrustTaxVideoState(MakerEntrustTaxVideoState.PENDING).updateById();
		return SmartResult.success();
	}

	public SmartResult verifyEntrustTaxVideo(BaseSimpleFormBean<VerifyEntrustTaxVideoFormBean> formBean) {
		VerifyEntrustTaxVideoFormBean reqdata = formBean.getReqdata();
		int userid = reqdata.getUserid();
		int state = reqdata.getState();
		String remark = reqdata.getRemark();

		MakerDetailDto userDetail = makerMapper.getUserDetail(userid);
		MakerStudio makerStudio = new MakerStudio().selectById(userid);
		Asserts.notNull(makerStudio, StatusMsg.StatusMsg_228);
		// 支持芜湖地区创客
		Asserts.equals(userDetail.getOpeningLocation(), 3, StatusMsg.StatusMsg_259);

		// 审核结果 1：通过 2：驳回
		if (state == 1) {
			makerStudio.setEntrustTaxVideoState(MakerEntrustTaxVideoState.VERIFIED).setEntrustTaxVideoRemark(remark);
		} else {
			makerStudio.setEntrustTaxVideoState(MakerEntrustTaxVideoState.REJECTED).setEntrustTaxVideoRemark(remark);
			// 发送消息给创客
			if (NumberUtil.equals(userDetail.getMakerType(), MakerType.INTELL)) {
				wxMessageService.notifyMakerEntrustTaxVideoRejected(makerStudio);
			} else if (NumberUtil.equals(userDetail.getMakerType(), MakerType.CROWDSOURCE)) {
				wxCrowdsourceMessageService.notifyMakerEntrustTaxVideoRejected(makerStudio);
			}
		}
		makerStudio.updateById();

		return SmartResult.success();
	}

	/**
	 * 查询所有友好创客
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult queryFriendlyMakerList(BaseSimpleFormBean<FriendlyMakerListFormBean> formBean) {
		FriendlyMakerListFormBean reqdata = formBean.getReqdata();
		Page<MakerAlipayDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());

		List<FriendlyMakerDto> list = makerMapper.queryFriendlyMakerList(reqdata.getCompname(), reqdata.getName(),
				reqdata.getFriendlyState(), reqdata.getInvoicescope(), reqdata.getIsOpenAliPay());

		// 查询创客项目总金额
		String entrustProjectStates = CalcAmountType.getEntrustProjectStates(CalcAmountType.PROCESSING);
		list.stream().forEach(dto -> {
			int userid = dto.getUserid();
			int nowYear = DateUtil.getNowYear();
			dto.setQuarterTotalAmount(coreProjectService.getUserQuarterTotalAmount(userid, CalcAmountType.PROCESSING));
			dto.setYearTotalAmount(coreProjectService.getUserYearlyTotalAmount(userid, CalcAmountType.PROCESSING));
			dto.setMonthTotalAmount(coreProjectService.getUserMonthlyTotalAmount(userid, CalcAmountType.PROCESSING));
			dto.setMonthEntrustAmount(
					entrustmentProjectItemMapper.sumUserMonthTotalAmountByStates(userid, 0, entrustProjectStates, 0, nowYear,
							DateUtil.getNowMonth()));
			dto.setQuarterEntrustAmount(entrustmentProjectItemMapper.sumUserQuarterTotalAmountByStates(userid, 0, entrustProjectStates, 0,
					nowYear, DateUtil.getNowQuater()));
			dto.setYearEntrustAmount(
					entrustmentProjectItemMapper.sumUserYearTotalAmountByStates(userid, 0, entrustProjectStates, 0, nowYear));
		});
		return SmartResult.ofPage(page);
	}

	public SmartResult<MakerStatusInfoDto> listMakers(BaseSimpleFormBean<AllMakerListFormBean> formBean) {
		AllMakerListFormBean reqdata = formBean.getReqdata();
		Date from = reqdata.getFrom();
		Date to = reqdata.getTo();
		String name = reqdata.getName();
		String phone = reqdata.getPhone();
		String bindcompname = reqdata.getBindcompname();
		Integer unifiedState = reqdata.getUnifiedState();
		Integer makerType = reqdata.getMakerType();
		Integer temporaryLogin = reqdata.getTemporaryLogin();
		Integer voluntary = reqdata.getVoluntary();
		Integer expertLabelState = reqdata.getExpertLabelState();
		Integer friendlyMaker = reqdata.getFriendlyMaker();
		Integer friendlyCompany = reqdata.getFriendlyCompany();
		Integer isOpenAlipay = reqdata.getIsOpenAlipay();
		Integer partnerStudio = reqdata.getPartnerStudio();
		Integer openingLocation = reqdata.getOpeningLocation();

		Page<MakerStatusInfoDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		makerMapper.listMakers(from, to, name, phone, bindcompname, unifiedState, makerType, temporaryLogin, voluntary, expertLabelState,
				friendlyMaker, friendlyCompany, isOpenAlipay, partnerStudio, openingLocation,reqdata.getIsOpenAccNo2());

		return SmartResult.ofPage(page);
	}

	public void exportMakers(HttpServletResponse response, AllMakerListFormBean reqdata) {
		Date from = reqdata.getFrom();
		Date to = reqdata.getTo();
		String name = reqdata.getName();
		String phone = reqdata.getPhone();
		String bindcompname = reqdata.getBindcompname();
		Integer unifiedState = reqdata.getUnifiedState();
		Integer makerType = reqdata.getMakerType();
		Integer temporaryLogin = reqdata.getTemporaryLogin();
		Integer voluntary = reqdata.getVoluntary();
		Integer expertLabelState = reqdata.getExpertLabelState();
		Integer friendlyMaker = reqdata.getFriendlyMaker();
		Integer friendlyCompany = reqdata.getFriendlyCompany();
		Integer isOpenAlipay = reqdata.getIsOpenAlipay();
		Integer partnerStudio = reqdata.getPartnerStudio();
		Integer openingLocation = reqdata.getOpeningLocation();

		List<MakerStatusInfoDto> list = makerMapper.listMakers(from, to, name, phone, bindcompname, unifiedState, makerType,
				temporaryLogin,
				voluntary, expertLabelState, friendlyMaker, friendlyCompany, isOpenAlipay, partnerStudio, openingLocation,
				reqdata.getIsOpenAccNo2());

		EasyExcelUtil.download(response, "创客列表", MakerStatusInfoDto.class, list);
	}

	public SmartResult<MakerYearAmountDto> listYearAmounts(BaseSimpleFormBean<Integer> formBean) {
		Integer userid = formBean.getReqdata();
		List<MakerYearAmountDto> list = Lists.newArrayList();
		for (int i = 2019; i <= DateUtil.getNowYear(); i++) {
			list.add(coreProjectService.getUserYearAmounts(NumberUtil.safeInt(userid), CalcAmountType.CHECKED, i));
		}
		// 求和
		MakerYearAmountDto sum = list.stream().reduce(MakerYearAmountDto.of(null), MakerYearAmountDto::add);
		list.add(sum);
		return SmartResult.success(list);
	}

	/**
	 * 导出已完成工作室开户创客列表
	 */
	public void exportConfirmedStudio(HttpServletResponse response,MakerListFormBean reqdata,Integer userid){
		Integer makerType = reqdata.getMakerType();
		if (makerType == null || makerType == 0) makerType = MakerType.INTELL;
		Integer changedDefaultRate = reqdata.getChangedDefaultRate();
		if (changedDefaultRate == null) {
			changedDefaultRate = 0;
		}

		Integer quotaFlag = reqdata.getQuotaFlag();
		String name = reqdata.getName();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		String inviter = reqdata.getInviter();
		String bindcompname = reqdata.getBindcompname();
		Integer tradecategoryid = reqdata.getTradecategoryid();
		Integer isOpenAliPay = reqdata.getIsOpenAliPay();
		Integer isOpenAccNo2 = reqdata.getIsOpenAccNo2();
		String makerLabel = StringUtil.isEmpty(reqdata.getMakerLabel()) ? null : reqdata.getMakerLabel();
		Integer expertLabelState = reqdata.getExpertLabelState();
		// 增加 根据注册地 进行筛选
		Integer openingLocation = reqdata.getOpeningLocation();
		Integer temporaryLogin = reqdata.getTemporaryLogin();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();
		//添加筛选条件
		BaseSimpleFormBean<MakerListFormBean> formBean = new BaseSimpleFormBean<>();
		formBean.setUserid(userid);
		String dockingCity = conditionTemplate(formBean);
		List<StudioOpenDto> studioOpenList = makerStudioMapper.getStudioOpenList(makerType, 2, name, inviter, bindcompname, tradecategoryid, startDate, endDate, openingLocation,
				changedDefaultRate, addStudioDefaultRate(), dockingCity, temporaryLogin, expertLabelState, quotaFlag, isOpenAliPay,
				makerLabel, isOpenAccNo2);

		EasyExcelUtil.download(response, "已完成工作室开户创客列表", StudioOpenDto.class, studioOpenList);
	}
	/**
	 *特殊费率查询
	 * @param formBean
	 * @return
	 */
	public SmartResult<SpecialRatesDto> specialRates(BaseSimpleFormBean<Integer> formBean) {
		int userid = formBean.getReqdata();
		SpecialRatesDto dto = makerMapper.specialRates(userid);
		return smartResult(dto);
	}
	/**
	 *已开银行公户的创客列表
	 * @param formBean
	 * @return
	 */
	public SmartResult<BankCorporateMakerDto> bankCorporateMaker(BaseSimpleFormBean<BankCorporateMakerFormBean> formBean) {
		BankCorporateMakerFormBean reqdata = formBean.getReqdata();
		Page<BankCorporateMakerDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<BankCorporateMakerDto> list = makerStudioMapper.bankCorporateMaker(reqdata.getRealname(),
				reqdata.getBindcompname(),reqdata.getUsername(),addStudioDefaultRate(),reqdata.getPlatformHosting());
		return smartResultPage(page);
	}
	/**
	 * 公户是否平台托管
	 * @param formBean
	 * @return
	 */
	public SmartResult platformHosting(BaseSimpleFormBean<PlatformHostingFormBean> formBean) {
		PlatformHostingFormBean reqdata = formBean.getReqdata();
		Integer userId = reqdata.getUserid();
		Integer custodianId = reqdata.getCustodianId();
		if (userId == null){
			return smartResult(StatusMsg.StatusMsg_101);
		}

		Maker maker = makerMapper.selectById(userId);
		if (maker == null){
			return smartResult(StatusMsg.StatusMsg_201);
		}
		Integer custodianIds = maker.getCustodianId();
		if (reqdata.getPlatformHosting() == 1 ){
			if (custodianId == null){
				return smartResult(StatusMsg.StatusMsg_101);
			}
			SystemManager systemManager = managerMapper.selectById(custodianId);
			if (systemManager == null){
				return smartResult(StatusMsg.StatusMsg_1300);
			}
			maker.setPlatformHosting(reqdata.getPlatformHosting())
					.setCustodianId(custodianId).updateById();
			//添加变更记录
			String describes;
			CustodianModificationRecord custodianModificationRecord = new CustodianModificationRecord();
			if(custodianIds == null){
				describes =systemManager.getLoginname();
			}else {
				SystemManager systemManagers = managerMapper.selectById(custodianIds);
				describes ="托管人由"+systemManagers.getLoginname()+"变更为"+systemManager.getLoginname();
				custodianModificationRecord.setFrontDutyId(custodianIds);
			}
			custodianModificationRecord.setUserId(userId)
					.setOperatorId(formBean.getUserid())
					.setDescribes(describes).insert();
		}else{
			makerMapper.emptyCustodianId(userId,reqdata.getPlatformHosting());
		}
		return smartResult();
	}
	/**
	 * 托管变更记录
	 * @param formBean
	 * @return
	 */
	public SmartResult<CustodianModificationRecord> viewManagedChangeLog(BaseSimpleFormBean<Integer> formBean) {
		Integer userId = formBean.getReqdata();
		if (userId == null){
			return smartResult(StatusMsg.StatusMsg_101);
		}
		List<CustodianModificationRecord> getRecord = custodianModificationRecordMapper.getRecord(userId);
		return smartResult(getRecord);
	}

	/**
	 * 复制已实名创客
	 *
	 * @param formBean
	 * @return
	 */
	@Transactional
	public synchronized SmartResult copyTheRealName(BaseSimpleFormBean<ChangeStudioOpenAdressFormBean> formBean) {
		if (null == formBean || null == formBean.getReqdata() || 0 == formBean.getReqdata().getUserid() ||
				2 == formBean.getReqdata().getNewOpeningLocation()) {
			return errorParamSmartResult();
		}
		ChangeStudioOpenAdressFormBean reqdata = formBean.getReqdata();
		int userid = reqdata.getUserid();
		int newOpeningLocation = reqdata.getNewOpeningLocation();
		//原创客信息
		Maker maker = new Maker().selectById(userid);
		MakerAccount makerAccount = new MakerAccount().selectOne(Condition.create().eq("userid", userid));

		if (null == maker || null == makerAccount) {
			return smartResult(StatusMsg.StatusMsg_201);
		}
		MakerBankcard makerBankcard = new MakerBankcard().selectOne(
				Condition.create().eq("state", 1).eq("userid", userid).eq("accttype", 1));
		if (null == makerBankcard) {
			return smartResult(StatusMsg.StatusMsg_226);
		}
		//新增 Maker
		Maker newMaker = new Maker();
		BeanUtils.copyProperties(maker, newMaker);
		//更新时间
		newMaker.setCreatetime(new Date())
				.setPhone(maker.getPhone() + "+")
				.setOpenid("")
				.setTaxerOpenid("");
		if (!newMaker.setUserid(null).insert()) {
			throw SmartException.of(StatusMsg.StatusMsg_199);
		}
		//新增 MakerAccount
		MakerAccount newMakerAccount = new MakerAccount();
		BeanUtils.copyProperties(makerAccount, newMakerAccount);
		//设置更新时间
		newMakerAccount.setAcctid(null)
				.setUserid(newMaker.getUserid())
				.setOpeningLocation(newOpeningLocation)
				.setCreatetime(new Date())
				.setUpdatetime(new Date())
				.setIdno(makerAccount.getIdno() + "+");
		if (newMakerAccount.getOpenStarttime() != null) {
			newMakerAccount.setOpenStarttime(new Date());
		}
		if (newMakerAccount.getAuthSubmitTime() != null) {
			newMakerAccount.setAuthSubmitTime(new Date());
		}
		if (newMakerAccount.getAuthPassTime() != null) {
			newMakerAccount.setAuthPassTime(new Date());
		}
		if (!newMakerAccount.insert()) {
			throw SmartException.of(StatusMsg.StatusMsg_199);
		}

		if (makerBankcard != null) {
			//新增 zdd_maker_bankcard
			MakerBankcard newMakerBankcard = new MakerBankcard();
			BeanUtils.copyProperties(makerBankcard, newMakerBankcard);
			//设置更新时间
			newMakerBankcard.setId(null).setUserid(newMaker.getUserid()).setCreatetime(new Date());
			if (!newMakerBankcard.insert()) {
				throw SmartException.of(StatusMsg.StatusMsg_199);
			}
		}
		return smartResult();
	}
	public SmartResult<FindMakerDto> findUseridByIdno(BaseSimpleFormBean<String> formBean) {
		@Valid String idno = formBean.getReqdata();
		FindMakerDto dto = makerMapper.findUseridByIdno(idno);
		if (dto != null) return SmartResult.success(dto);
		return SmartResult.fail(StatusMsg.StatusMsg_201);
	}

	public SmartResult<FindMakerByNameDto> findMakersByName(BaseSimpleFormBean<String> formBean) {
		@Valid String name = formBean.getReqdata();
		List<FindMakerByNameDto> dto = makerMapper.findMakersByName(name);
		return smartResult(dto);
	}


	/**
	 * 添加创客状态原因
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult addMakerStatusReason(BaseSimpleFormBean<MakerStatusReason> formBean) {
		MakerStatusReason reqdata = formBean.getReqdata();
		if (reqdata.getUserid() == null || reqdata.getUserid() == 0)
			return errorParamSmartResult();
		MakerStatusReason makerStatusReason = new MakerStatusReason().selectOne(Condition.create().eq("userid", reqdata.getUserid()));
		if (makerStatusReason != null ){
			if (reqdata.getAccountOpeningReason() != null)
				makerStatusReason.setAccountOpeningReason(reqdata.getAccountOpeningReason());
			if (reqdata.getOpenedReason() != null)
				makerStatusReason.setOpenedReason(reqdata.getOpenedReason());
			if (reqdata.getRealNameReason() != null)
				makerStatusReason.setRealNameReason(reqdata.getRealNameReason());
			makerStatusReason.updateById();
		}else {
			reqdata.insert();
		}
		return smartResult();
	}

	public void compressIdNoFileById(HttpServletResponse response, int companyId) throws IOException {
		if (0 == companyId) {
			LogUtil.error("根据自然人ID压缩身份证文件-参数错误！");
			return;
		}
		//新建一个临时文件夹，将后续所有文件夹都放在这个文件夹下
		String temporaryFolderName = "temporaryFolder" + System.currentTimeMillis();
		File temporaryFolderFile = new File("/usr/local/" + temporaryFolderName);
		if (!temporaryFolderFile.exists()) {
			if (!temporaryFolderFile.mkdirs()) {
				LogUtil.error("新建总的临时文件夹失败！");
				return;
			}
		}
		List<MakerAccount> list = makerAccountMapper.getMakerIdno(companyId);

		for (MakerAccount dto : list) {
			//新建文件夹存放身份证图片信息
			String folderFileName = dto.getRealname() + "+" + dto.getIdno();
			File folderFile = new File("/usr/local/" + temporaryFolderName + "/" + folderFileName);
			if (!folderFile.exists()) {
				if (!folderFile.mkdirs()) {
					LogUtil.error("新建存放身份证图片的文件夹失败！文件夹名称：" + folderFileName);
					continue;
				}
			}
			//复制身份证文件
			copyIdNoFile(dto, temporaryFolderName, folderFileName);
		}
		LogUtil.info("====================开始压缩文件====================");
		OutputStream out = response.getOutputStream();
		try {
			// 调用方法打包zip文件
			byte[] data = FileUtil.createZip(temporaryFolderFile.getPath());
			// 压缩包名称
			String downloadName = "创客身份文件信息.zip";
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(downloadName, "utf-8"));
			response.addHeader("Content-Length", "" + data.length);
			response.setContentType("application/octet-stream;charset=UTF-8");
			IOUtils.write(data, out);
		} catch (Exception e) {
			LogUtil.error("将文件夹压缩为压缩包失败！");
		} finally {
			try {
//				// 压缩成功后删除项目中文件夹
//				if (temporaryFolderFile.exists()) {
//					FileUtil.delFiles(temporaryFolderFile);
//				}
				if (out != null) {
					out.flush();
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				LogUtil.error("根据创客ID压缩身份证文件-将文件夹压缩为压缩包出现异常！");
			}
		}
		LogUtil.info("====================压缩文件结束====================");
	}

	public void copyIdNoFile(MakerAccount dto, String temporaryFolderName, String folderFileName) {
		//获取身份证正面信息
		 if (null != dto.getIdfrontimg()) {
			File positive = new File("/usr/local/oss/zdd-img/" + dto.getIdfrontimg());
			//获取文件名
			String fileName = dto.getIdfrontimg().substring(dto.getIdfrontimg().lastIndexOf("/"));
			//new一个空的File用来复制
			File copyPositive = new File("/usr/local/" + temporaryFolderName + "/" + folderFileName + fileName);
			try {
				Files.copy(positive.toPath(), copyPositive.toPath());
			} catch (Exception e) {
				LogUtil.error("身份证人像面复制失败！创客ID：" + dto.getUserid());
			}
		} else {
			LogUtil.error("创客没有身份证人像面图片！创客ID：" + dto.getUserid());
		}
		if (null != dto.getIdbackimg()) {
			File back = new File("/usr/local/oss/zdd-img/" + dto.getIdbackimg());
			//获取文件名
			String fileName = dto.getIdbackimg().substring(dto.getIdbackimg().lastIndexOf("/"));
			//new一个空的File用来复制
			File copyBack = new File("/usr/local/" + temporaryFolderName + "/" + folderFileName + fileName);
			try {
				Files.copy(back.toPath(), copyBack.toPath());
			} catch (Exception e) {
				LogUtil.error("身份证国徽面复制失败！创客ID：" + dto.getUserid());
			}
		} else {
			LogUtil.error("创客没有身份证国徽面图片！创客ID：" + dto.getUserid());
		}
	}

	//创客生日祝福短信发送
	public void sendMakerBirthSms() {
		if (!ContextUtil.isProd()) {
			return;
		}
		List<MakerBriefDto> dtos = makerMapper.getMakerBirth();
		for (MakerBriefDto dto : dtos) {
			commonService.sendBirthSms(dto.getPhone());
		}
	}

	//创客周年纪念短信发送
	public void sendMakerAnniversarySms() {
		if (!ContextUtil.isProd()) {
			return;
		}
		List<MakerBriefDto> dtos = makerMapper.getMakerAnniversary();
		for (MakerBriefDto dto : dtos) {
			commonService.sendAnniversarySms(dto.getPhone(), dto.getYear());
		}
	}

}